简体   繁体   中英

Split string into parts of 3 words Java

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?

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]);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM