Java split String - Split a String into tokens with StringTokenizer

Java String FAQ: How do I split a String into substrings?

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.

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:

I hope this Java "split string" tutorial has been helpful.

Permalink

Hi Alvin,

thanks, this helped me much. ;-)

Permalink

"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

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.