Split String using Tokenizer in Java

In this tutorial we show you how to split a string in Java. We explore the usage of String#split(regex) method and the StringTokenizer class. The first one is recommended to use in future projects.

Split a string using String#split(regex)

Since JDK 1.4 there is a String#split(regex) method for splitting strings in chunks.

package com.memorynotfound.date;

public class SplitStringExample {

    public static void main(String... args) {

        String example = "string-to-be-split";
        String output[] = example.split("-");

        for (int i = 0; i < output.length; i++){
            System.out.println("part " + i + ": " + output[i]);
        }

    }
}
Info
When working with characters that need to be escaped use the java.util.regex.Pattern#quote(string) method.

Generated output.

part 0: string
part 1: to
part 2: be
part 3: split

Split a string using StringTokenizer

The StringTokenizer is available since JDK 1.0. and has the same functionality as the String#split(regex) method. The string.split method is recommend to use in future projects.

package com.memorynotfound.date;

import java.util.StringTokenizer;

public class StringTokenizerExample {

    public static void main(String... args) {

        String example = "string-to-be-split";
        StringTokenizer tokenizer = new StringTokenizer(example, "-");

        int i = 0;
        while (tokenizer.hasMoreTokens()){
            System.out.println("part " + i + ": " + tokenizer.nextToken());
            i++;
        }

    }
}

Generated output.

part 0: string
part 1: to
part 2: be
part 3: split

References

Download

Download it ! – split string java

You may also like...