Java String split
The java string split() method splits a string according a given regular expression and returns a char array.
There are two signature for split() method in java string.
public String split(String regex)
public String split(String regex, int limit)
regex : regular expression or delimiter value to be applied on string.
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching regex.
In the first signature of split() method, the string on which split method is called, whenever the delimiter value i.e regex is encountered, the string is split at that point. All the chopped strings at the end are added into a String type array and that array is returned to the calling function.
In the second signature of split() method, the only difference is the second parameter i.e limit is the number of split strings stored in the returned array of strings.
// A Java program for splitting a string using split()
import java.io.*;
public class Test
{
public static void main(String args[])
{
String Str = new String("First-Demo-Example");
for (String val: Str.split("-", 2)) // Split above string in at-most two strings
System.out.println(val);
System.out.println("");
for (String val: Str.split("-")) //Splits str into all possible tokens
System.out.println(val);
}
}
Output:
First
Demo-Example
First
Demo
Example
0 Comment(s)