Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. How can I split a string with multiple spaces on every nth space? [duplicate]

Tags:

java

string

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");
like image 823
TheMightyLlama Avatar asked Dec 06 '13 16:12

TheMightyLlama


2 Answers

You could do:

String[] stringArray = string.split("(?<!\\G\\S+)\\s");
like image 108
Reimeus Avatar answered Nov 15 '22 10:11

Reimeus


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
like image 31
Pshemo Avatar answered Nov 15 '22 11:11

Pshemo