String split example in java

This example shows you the use of split method of String class.

package com.java.connect.string;
 
// String split example in java
public class StringSplitExample {
    public static void main(String[] args) {
        //
        // declare the String with some text
        //
        String string = "Some string here to split";
        //
        // Decalre the delimiter to split given string
        // We have sapce char as delimiter
        String delimiter = " ";
        //
        // given string will be split by the argument delimiter provided.
        //
        String[] array = string.split(delimiter);
        // Print substrings splitted array of string
        for (int i = 0; i < array.length; i++)
            System.out.println(array[i]);
 
        //
        // Using second argument in the String.split() method,
        // We can control the maximum
        // number of substrings generated by splitting a string.
        //
        array = string.split(delimiter, 3);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}

The output of above example will be as:

Some
string
here
to
split
Some
string
here to split