Split a String

This tutorial shows how to split a string in Java.

Below, we present three options to split a string in Java namely – with StringTokenizer class, with split() method of the String class and with Pattern class. Each of the options has its utility and advantage over the other. You can use either of them as per your need.

Split a string with StringTokenizer

The StringTokenizer class allows splitting a given string around a given delimiter. The delimiter could be a single character or a sequence of characters but not a regular expression.

There are a couple of important points to note here. The StringTokenizer does not scan the entire string before hand to create tokens. Instead, it scans for tokens one at time. Due to this, it can allow changing the delimiter after every token, as and when needed. This is a very unique and powerful feature that allows tokenizing strings having different delimiters.

In the code snippet above,  the delimiter could be changed as we progress along the string, if needed. If the delimiter isn’t changing then the tokenizer can be created with both the input string and the delimiter and then can call the nextToken() method without any parameter.

Output

Split a string with String.split()

The String class allows splitting the string around a delimiter that could be expressed as a regular expression. This gives more flexibility in specifying the delimiter as opposed to a constant delimiter string allowed in StringTokenizer. However, this flexibility does come with a performance impact.

Another significant difference between String.split() and StringTokenizer is that the String.split() scans the entire string at once and returns all the tokens as an array. Also, the flexibility to change the delimiter that existed in StringTokenizer isn’t available here.

Output

Split a string with Pattern class

The Pattern class holds a compiled regular expression as the delimiter and allows splitting a given string around the matches of the expression in the same way as String.split() does. But, the advantage here is that once a delimiter is compiled it can be used to split multiple strings, thereby, giving significant performance improvement over String.split() if large number of strings are to be split using the same delimiter.

Output


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Previous article

Java String to Int

Next article

Install Webmin on AWS EC2 server