6

Here's a sample string which I intend to split into an array:

Hello My Name Is The Mighty Llama

The output should be:

Hello My
Name Is
The Mighty
Llama

The below splits on every space, how can I split on every other space?

String[] stringArray = string.split("\\s");
TheMightyLlama
  • 1,243
  • 1
  • 19
  • 51

2 Answers2

10

You could do:

String[] stringArray = string.split("(?<!\\G\\S+)\\s");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

While this is possible to use split to solve it like this one I strongly suggest using more readable way with Pattern and Matcher classes. Here is one of examples to solve it:

String string="Hello My Name Is The Mighty Llama";
Pattern p = Pattern.compile("\\S+(\\s\\S+)?");
Matcher m = p.matcher(string);
while (m.find())
    System.out.println(m.group());

output:

Hello My
Name Is
The Mighty
Llama
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269