Reputation: 184
I want to split a string into parts of 3 words in Java.
For example:
I want to walk in the park with my father
I want to have a string: "I want to"
, and another string:"walk in the"
, etc.
How would I do this?
Upvotes: 3
Views: 2279
Reputation: 3323
Here is a solution using RegEx
String sentence = "I want to walk in the park with my father";
Pattern pattern = Pattern.compile("\\w+ \\w+ \\w+ ");
Matcher matcher = pattern.matcher(sentence);
while (matcher.find()) {
System.out.println(matcher.group());
}
Notice that whit this expression the last word 'father' is not matched.
For the non-RegEx solution, I would use something like this
String sentence = "I want to walk in the park with my father";
String[] words = sentence.split(" ");
List<String> threeWords = new ArrayList<>();
int length = words.length;
for (int ind = 2; ind < length; ind += 3) {
threeWords.add(words[ind - 2] + " " + words[ind - 1] + " " + words[ind]);
}
if (length % 3 == 1) {
threeWords.add(words[length - 1]);
} else if (length % 3 == 2) {
threeWords.add(words[length - 2] + " " + words[length - 1]);
}
Upvotes: 4
Reputation: 417
For me creating a temporary ArrayList (aka words
), and removing 3 words at a time, concatenating them into a String, and adding it to my final ArrayList worked just fine, although this probably isn't extremely performance efficient, it gets the job done & it's simple to understand.
// finalWords is your result
ArrayList<String> finalWords = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
for(String str : "I want to walk in the park with my father".split(" "))
words.add(str);
while(words.size() > 0)
{
String str = "";
for(int i = 0; i < 3; i++)
{
if(words.size() > 0)
{
str += words.get(0) + " ";
words.remove(0);
}
}
finalWords.add(str);
}
EDIT: Since you wrote this:
I know how to split it in individual words, but not into groups.
in the comments, splitting it into groups of words is simple. First, you split your sentence into words, then you concatenate those words into new strings, 3 at a time, and add the concatenated strings to a list/array of your choice.
Upvotes: 1