Split a string
Java, Programming February 1st, 2007Split method in String class will break a string into tokens or array. By specify regular expression as delimiters, as the example below.
Split a string into array, a space as delimiter.
String str = "This is a test string"; String[] words = str.split(" "); for (int i=0; i < words.length; i++) System.out.println(words[i]);
Output:
This
is
a
test
string
In some case that delimiter has a special meaning in a regular expression. You must add two backslashes (\\..) in front of the delimiter to make it as a character rather than the wildcard in a regular expression. Some examples of delimiter that has a special meaning are a dot(.), a star(*) , ‘|’ etc.
For a dot, must use delimiter as “\\.”
String str = "123.456.789.10.11";
String[] words = str2.split ("\\.");
for (int i=0; i < words.length; i++)
System.out.println(words[i]);
The special character needs to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another.
Related post
No related posts.




September 26th, 2007 at 7:46 pm
Ehm if you are going to use String alteration methods and such… and more then once you could probably better use
StringUtils from
http://commons.apache.org/lang/