Update: I updated this tutorial in late 2012 after the note from Pablo Souza in the Comments section showing that the StringTokenizer class is now a "legacy class."
To split a string in Java into substrings, use the splitmethod of the String class. For instance, given the following string:
String speech = "Four score and seven years ago";
You can split the string into substrings using the following line of code:
String[] result = speech.split("\\s");
More accurately, that expression will split the string into substrings, where the substrings are separated by whitespace characters. For this example, it serves the purpose of breaking the string into words.
The string \sis a regular expression that means "whitespace", and you have to write it with two backslash characters ("\\s") when writing it as a string in Java.
If you print these results with a Java for loop, like this:
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
You'll see the following output:
Four score and seven years ago
To help you see how this works, and experiment with it yourself, here's the source code for a complete example:
/** * A Java String split example. * By Alvin Alexander, http://alvinalexander.com */ public class Main { public static void main(String[] args) { String speech = "Four score and seven years ago"; String[] result = speech.split("\\s"); for (int x=0; x<result.length; x++) { System.out.println(result[x]); } } }
If you want to split by a "normal" character when using the splitmethod, just specify that character as a string in double quote when calling split. For instance, given the following string, which is separated by ":" characters:
String s = "Alvin:Alexander:Talkeetna:Alaska";
You would split it into substrings with this line of code:
String[] result = s.split(":");
You could then print it using the for loop shown earlier.
Many thanks to Pablo Souza for sharing the comment that this article needed to be updated. For more information on the Java String split method, and regular expressions, see the following links:
I hope this Java "split string" tutorial has been helpful.
Thanks
Hi Alvin,
thanks, this helped me much. ;-)
omg just perfect as with all
omg just perfect as with all ur other tutorials..thanks so much
I thank you for this. I've
I thank you for this. I've been looking for solution for my problem for days.
"StringTokenizer is a legacy
"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code"
http://docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
Thank you
Pablo - Thank you for letting me know about this. The original article was written a long time ago, and I just updated it to use the 'split' method of the String class.
Post new comment