Quick example:
public class Test {
public static void main(String[] args) {
String str = " a b";
String[] arr = str.split("\\s+");
for (String s : arr)
System.out.println(s);
}
}
I want the array arr to contain 2 elements: "a" and "b", but in the result there are 3 elements: "" (empty string), "a" and "b". What should I do to get it right?
Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.
To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.
You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string. var hello = ' Hello there! '; // returns "Hello there!" hello.
Use the string. slice() method to get the first three characters of a string, e.g. const first3 = str. slice(0, 3); . The slice method will return a new string containing the first three characters of the original string.
Kind of a cheat, but replace:
String str = " a b";
with
String[] arr = " a b".trim().split("\\s+");
The other way to trim it is to use look ahead and look behind to be sure that the whitespace is sandwiched between two non-white-space characters,... something like:
String[] arr = str.split("(?<=\\S)\\s+(?=\\S)");
The problem with this is that it doesn't trim the leading spaces, giving this result:
a
b
but nor should it as String#split(...)
is for splitting, not trimming.
The simple solution is to use trim()
to remove leading (and trailing) whitespace before the split(...)
call.
You can't do this with just split(...)
. The split regex is matching string separators; i.e. there will necessarily be a substring (possibly empty) before and after each matched separator.
You can deal with the case where the whitespace is at the end by using split(..., 0)
. This discards any trailing empty strings. However, there is no equivalent form of split
for discarding leading empty strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With