Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

split

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?

like image 773
Range Avatar asked Jan 16 '11 20:01

Range


People also ask

Can a string be split?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string into multiple parts?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

How do you split a string around a space?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.


2 Answers

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

like image 75
Nikita Rybak Avatar answered Nov 14 '22 23:11

Nikita Rybak


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

like image 29
Jim Huang Avatar answered Nov 15 '22 00:11

Jim Huang