Java String FAQ: How do I split a String into substrings?
To split a string in Java into substrings, use the split
method 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 \s
is 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
A complete split string example
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 split
method, 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.
Thanks
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:
- The String class
- The Java Pattern class shares regular expression examples
I hope this Java "split string" tutorial has been helpful.