开发者

Is it possible to split a String around "." in java?

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 wit开发者_如何学JAVAh punctuation marks?


split takes regex. Try split("\\.").


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜