Reputation: 613
How would I split a string upon one or more spaces in between, preserving the effect of having more than one space.
e.g. when the input string is:
s = "a bc de fg ";
spl = s.split(" ");
gives me the array
{a, bc, de, fg}.
how do I get the same array to 1-or-more spaces in between, like
s = "a bc de fg ";
TIA.
Upvotes: 0
Views: 51
Reputation: 174844
Just split the string using the below regex,
String tok[] = s.split(" +");
System.out.println(Arrays.toString(tok));
<space>+
matches one or more spaces.
Upvotes: 2
Reputation: 70750
You can use the +
quantifier meaning "one or more".
String s = "a bc de fg ";
String[] parts = s.split(" +");
System.out.println(Arrays.toString(parts)); // [a, bc, de, fg]
You may also consider using \s
which matches any white space character.
String[] parts = s.split("\\s+");
Upvotes: 3