When I try to split a String around occurrences of "." the method split returns an array of strings with length 0.When I split around occurrences of "a" it works fine.Does anyone know why?Is split not supposed to work with punctuation marks?
Asked
Active
Viewed 3,405 times
2 Answers
16
split takes regex. Try split("\\.")
.

Nikita Rybak
- 67,365
- 22
- 157
- 181
-
2
-
+1, or StringUtils.split -> http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#split(java.lang.String,%20char) – unbeli Jan 16 '11 at 20:17
-
They should have called it splitByRegex and keep a simple split method that takes a String ! Nearly every Java developer once lost time with this one... This would respect the principle of least surprise. – Christophe Roussy Dec 20 '12 at 14:14
2
String a = "a.jpg";
String str = a.split(".")[0];
This will throw ArrayOutOfBoundException because split accepts regex arguments and "." is a reserved character in regular expression, representing any character. Instead, we should use the following statement:
String str = a.split("\\.")[0]; //Yes, two backslashes
When the code is compiled, the regular expression is known as "\.", which is what we want it to be
Here is the link of my old blog post in case you are interested: http://junxian-huang.blogspot.com/2009/01/java-tip-how-to-split-string-with-dot.html

Jim Huang
- 401
- 5
- 9