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,051
  • 1
  • 16
  • 42

2 Answers2

8

You could do:

String[] stringArray = string.split("(?<!\\G\\S+)\\s");
Reimeus
  • 155,977
  • 14
  • 207
  • 269
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
  • 118,400
  • 24
  • 176
  • 257