AmacOS
AmacOS

Reputation: 311

After each word which ends with given substring insert a word

I need after each word of the text, ending with a given substring, insert the specified word.My code works to some extent, I think it is not good idea modifying StringBuilder object while iterating over it. As you can see it fails in the last two cases, with "kalola" and "lalilo". Thanks a lot!

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextEditor {

    public static void main(String[] args) {

        String text = "Hello Mister James! Do you use trello fregiently? "
                + "Do you know Canelo Pavelo magenta ravelo sagenta! "
                + "lolita kalola lalilo lalita 333l lo.";

        String regex = "\\b\\w+lo\\b";

        String word = " 232 ";

        StringBuilder copyOfText = new StringBuilder(text);

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(copyOfText);

        while(matcher.find()) {
            copyOfText.insert(matcher.end(), word);
        }

        //text = copyOfText.toString();

        System.out.println(copyOfText);
    }
}

Received output is:

Hello 232 Mister James! Do you use trello 232 fregiently? Do you know Canelo 232 Pavelo 232 magenta ravelo 232 sagenta! lolita kalo 232 la lalilo lalita 333l lo.

Expected output is:

Hello 232 Mister James! Do you use trello 232 fregiently? Do you know Canelo 232 Pavelo 232 magenta ravelo 232 sagenta! lolita kalola lalilo 232 lalita 333l lo.

Upvotes: 1

Views: 222

Answers (1)

Juan Carlos Mendoza
Juan Carlos Mendoza

Reputation: 5794

As mentioned in the comments you can use String.replaceAll instead of iterating with a while loop:

String text = "Hello Mister James! Do you use trello fregiently? "
        + "Do you know Canelo Pavelo magenta ravelo sagenta! "
        + "lolita kalola lalilo lalita 333l lo.";

String word = "232";

System.out.println(text.replaceAll("(\\w+lo\\b)", "$1 " + word));

Output:

Hello 232 Mister James! Do you use trello 232 fregiently? Do you know Canelo 232 Pavelo 232 magenta ravelo 232 sagenta! lolita kalola lalilo 232 lalita 333l lo.

Upvotes: 1

Related Questions