Question
How can I use '.' as the delimiter with String.split() in Java?
String[] words = line.split("\.");
Answer
In Java, using `String.split()` with a dot (`.`) as a delimiter can lead to unexpected behavior due to the nature of regular expressions, where the dot is a special character matching any character. To split a string by an actual dot, you need to escape it properly in the regular expression.
String[] words = line.split("\\."); // Correct usage to split by '.'
Causes
- The dot (`.`) in Java's regular expressions represents 'any character', which causes `String.split()` to not work as intended when used directly without escaping.
- Not escaping the dot leads to issues like ArrayOutOfBounds exceptions when accessing array indices that don't exist.
Solutions
- Use `line.split("\\.")` to escape the dot properly, which matches only actual dots in the string.
- Alternatively, use `line.split(Pattern.quote("."))` to treat the dot as a literal string, avoiding regular expressions altogether.
Common Mistakes
Mistake: Using `line.split(".")` without escaping the dot.
Solution: Always escape the dot using `line.split("\\.")` or use `Pattern.quote(".")`.
Mistake: Assuming the split operation will return a valid array without checking its length before accessing indices.
Solution: Always check the length of the resulting array before accessing elements.
Helpers
- Java String split
- Java split method
- Java dot delimiter
- Java regular expressions