Core Java >> Strings


Spit String Java Tutorial


A string is usually required to be split into small chunks (words,keywords) based on some criteria. This is required in case of getting particular information from a bigger string. Here I will show how to split a string in Java with example code.


1) Using the split() method:

Here is the sample code which shows how to use the split() method of String class

package com.example;

public class Test{

    public static void main(String[] args) throws InterruptedException {
        String str = "This is a Test";
        String split[] = str.split(" ");
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
        }
    }
}

Output:

This
is
a
Test

When using the split method one can pass any valid regular expression as argument to this method and this method will then split the string object based on the argument being passed.

The internal implementation of split method in String class uses the Pattern and Matcher classes from the java.util.regex package

2) Using StringTokenizer class

package com.example;

import java.util.StringTokenizer;

public class Test{

    public static void main(String[] args) throws InterruptedException {
        String str = "This is a Test";
        StringTokenizer stn = new StringTokenizer(str);
        while(stn.hasMoreTokens()) {
            System.out.println(stn.nextToken());
        }
    }
}

Output:

This
is
a
Test

StringTokenizer class doesn’t use regular expressions to generate the String tokens out of the String object.

Which String split method to use:

Now we have seen that there are two ways to split a String based on delimiters in Java. But each one of them should be used in special cases

split() method:

When a quick wayout is required to get the words in array format, use the split() method of String class to get the tokens. The split method returns String array and hence one can access the tokens by using 0 based index and also pass this String array to some method expecting an String array as argument.

StringTokenizer:

StringTokenizer generates the tokens of String objects and stores them internally. The best point about using StringTokenizer class is that one can reuse the tokens once generated. This is because of the fact that when a String is tokenized then the same token objects are reused second time onwards.

Java String Tutorials
Insert Update Blob Database
Legacy Application Liferay

Comments

Javin @ java classpath tutorial

December 18, 2011 3:13 pm

Nice tutorial Sandeep.

split

January 30, 2012 3:13 pm

great small but effictive split tutorial!
thank you a lot!

Leave Comment