java String

String split() in Java Code With Examples

Table of Contents

Program


public class StringSplit 
{
	public static void main(String[] args) 
	{
		    String c1 = "Dh,o,n.i";
		    String delimiters = "\\s+|,\\s*|\\.\\s*";
		    String[] tokenVal = c1.split(delimiters);
		    System.out.println("1. String Split(String regex)");
	            System.out.println("Count : " + tokenVal.length);
            for (String token : tokenVal)
	    {
                    System.out.print(token);
	    }
		    System.out.println("");
		    String c2 = new String("Welcome-to-Marvel-And-Dc-World");
		    System.out.println("2. String Split(String regex,int toffset)");
		    System.out.print("Return : ");
	    for (String retval : c2.split("-", 2)) 
	    {
		    System.out.println(retval);
	    }
		    System.out.print("Return 2 : ");
	    for (String retval : c2.split("-", 5)) 
	    {
		    System.out.println(retval);
	    }
	}
}

Output

1. String Split(String regex)
                Count : 4
                Dhoni
	     2. String Split(String regex,int toffset)
		Return : Welcome
		to-Marvel-And-Dc-World
		Return 2 : Welcome
		to
		Marvel
		And
		Dc-World

Description

Split:

public String[] split​(String regex)

Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Parameters:

regex – the delimiting regular expression

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Throws:

PatternSyntaxException – if the regular expression’s syntax is invalid

Since:

1.4

public String[] split​(String regex, int limit)

Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

Parameters:

regex – the delimiting regular expression
limit – the result threshold, as described above

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Throws:

PatternSyntaxException – if the regular expression’s syntax is invalid

Since:

1.4