0

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.

1
  • just split the string using the regex ` +` Commented Aug 30, 2014 at 2:01

2 Answers 2

3

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+");
Sign up to request clarification or add additional context in comments.

1 Comment

The * quantifier means "zero or more"
2

Just split the string using the below regex,

String tok[] = s.split(" +");
System.out.println(Arrays.toString(tok));

<space>+ matches one or more spaces.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.