Quick Reach
The split method of Java
The Java split method of the String class is used to split the given string. The whole string will be broken by the given regular expression (regex).
The split method can be used to limit the breaking of the string by providing an int number (example shown below).
See a string split example online
Syntax of the split method
The syntax of using the split Java method to split a string completely is:
public String[] split(String “regex”)
Return Value of the split method:
The split method returns an array of strings, containing the broken string.
Java string split method example
The example below uses the split method of the String class and breaks a string completely by a given regular expression; “and” in that case. The example uses a “foreach” loop for displaying the array items created after the split method.
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class string_example {
public static void main(String []args) {
String Strex;
Strex ="name is: Mike and age is: 30 and salary is: $5000";
for (String Strsplit: Strex.split(" and ")){
System.out.println(Strsplit);
}
}
}
|
The output will be:
name is: Mike
age is: 30
salary is: $5000
The string is broken from the “ and “ into 3 items. Then Java foreach loop is used to display items in the returned array.
Limiting split of the string
As shown in the above example, the whole string is broken by the given regex. What if you want to limit the number of splits. For example, see a string below:
“name is: Mike and age is: 30 and salary is: $5000”
What if we want to split this from “ and “ for its first occurrence only? To achieve that, we can limit the string split by giving an int number as shown below.
Syntax of limiting the split of string
Following is the syntax of including an int number to limit the string split in Java.
public String[] split(String “regex”, int number)
The split example with limit parameter
The example below uses the split method of string with a given regular expression and the Limit number parameter. The for loop is used to display string after the split method:
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class string_example {
public static void main(String []args) {
String Strex;
Strex ="name is: Mike and age is: 30 and salary is: $5000";
for (String Strsplit: Strex.split(" and ",2)){
System.out.println(Strsplit);
}
}
}
|
The output will be:
name is: Mike
age is: 30 and salary is: $5000
As you can see, the string split method only broken the given string into two “pieces” as this is specified in the split method.
Also see: Java strings
Leave A Comment?