How to split a string with any whitespace chars as delimiters
In Java, you can use the split()
method of the String
class to split a string based on a regular expression. To split a string on any whitespace characters (such as space, tab, or newline), you can use the regular expression "\\s+"
.
Here is an example of how to split a string on any whitespace characters:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String s = "a b\tc d\ne f";
String[] parts = s.split("\\s+");
System.out.println(Arrays.toString(parts)); // Outputs "[a, b, c, d, e, f]"
}
}
This code uses the split()
method to split the string s
on any sequence of one or more whitespace characters. The resulting array contains the parts of the string that were separated by the delimiters.
It is important to note that the split()
method uses a regular expression to specify the delimiters, so you need to use \\s+
instead of just \\s
to match any number of consecutive whitespace characters.