class Main {
public static void main(String[] args) {
String text = "Java is a fun programming language";// split string from space
String[] result = text.split(" ");
System.out.print("result = ");
for (String str : result) {
System.out.print(str + ", ");
}
}
}// Output: result = Java, is, a, fun, programming, language,
Example 1: split() Without limit Parameter
// importing Arrays to convert array to string
// used for printing arrays
import java.util.Arrays;class Main {
public static void main(String[] args) {
String vowels = "a::b::c::d:e";// splitting the string at "::"
// storing the result in an array of strings
String[] result = vowels.split("::");
// converting array to string and printing it
System.out.println("result = " + Arrays.toString(result));
}
}
Example 2: split() With limit Parameter
// importing Arrays to convert array to string
import java.util.Arrays;class Main {
public static void main(String[] args) {
String vowels = "a:bc:de:fg:h";// splitting array at ":"
// limit is -2; array contains all substrings
String[] result = vowels.split(":", -2);System.out.println("result when limit is -2 = " + Arrays.toString(result));
// limit is 0; array contains all substrings
result = vowels.split(":", 0);
System.out.println("result when limit is 0 = " + Arrays.toString(result));// limit is 2; array contains a maximum of 2 substrings
result = vowels.split(":", 2);
System.out.println("result when limit is 2 = " + Arrays.toString(result));// limit is 4; array contains a maximum of 4 substrings
result = vowels.split(":", 4);
System.out.println("result when limit is 4 = " + Arrays.toString(result));// limit is 10; array contains a maximum of 10 substrings
result = vowels.split(":", 10);
System.out.println("result when limit is 10 = " + Arrays.toString(result));
}
}
result when limit is -2 = [a, bc, de, fg, h]
result when limit is 0 = [a, bc, de, fg, h]
result when limit is 2 = [a, bc:de:fg:h]
result when limit is 4 = [a, bc, de, fg:h]
result when limit is 10 = [a, bc, de, fg, h]