Java – String split() Example, Strings split() program

String can be broken into a pieces with the help of split() method in java. split() method returns a value in String array. String can be split on regular expression and all tokens are saved in a string array form. This array can easily get from any loop. Use of String split() in java is shown below.

Example of String split() in java, JSP

public class StringSplitExampleJava {

    public static void main(String[] args) {

        //@ 1st split Example
        String string1 = "This is Java split String";

        String[] str1 = string1.split(" ");

        System.out.println("Length1 :"+str1.length);

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

        //@ 2nd split Example

        String string2 = "Java, split, String";

        String[] str2 = string2.split(",");

        System.out.println("Length2 :"+str2.length);

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

Output

Length1 :5
Split1 Element 0 :This
Split1 Element 1 :is
Split1 Element 2 :Java
Split1 Element 3 :split
Split1 Element 4 :String
Length2 :3
Split2 Element 0 :Java
Split2 Element 1 : split
Split2 Element 2 : String

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post