Skip to content Skip to sidebar Skip to footer

How To Replace Multiple Substring Of A String At One Time?

I hope to replace two substring in the String s, so I write the following code. I think the efficiency is too low in my code when S is a huge string. Can I replace multiple substri

Solution 1:

If you want to only perform one search of s, you can either do your own indexOf() loop, or use a regular expression replacement loop.

Here is an example of using a regular expression replacement loop, which uses the appendReplacement() and appendTail() methods to build the result.

To eliminate the need for doing a string comparison to figure out which keyword was found, each keyword is made a capturing group, so existence of keyword can be quickly checked using start(int group).

Strings="This %ToolBar% is a %Content%";

StringBufferbuf=newStringBuffer();
Matcherm= Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s);
while (m.find()) {
    if (m.start(1) != -1)
        m.appendReplacement(buf, "Edit ToolBar");
    elseif (m.start(2) != -1)
        m.appendReplacement(buf, "made by Paul");
}
m.appendTail(buf);
System.out.println(buf.toString()); // prints: This Edit ToolBar is a made by Paul

The above runs in Java 1.4 and later. In Java 9+, you can use StringBuilder instead of StringBuffer, or you can do it with a lambda expression using replaceAll​():

String s = "This %ToolBar% is a %Content%";

String result = Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s)
        .replaceAll(m -> (m.start(1) != -1 ? "Edit ToolBar" : "made by Paul"));
System.out.println(result); // prints: This Edit ToolBar is a made by Paul

A more dynamic version can be seen in this other answer.

Post a Comment for "How To Replace Multiple Substring Of A String At One Time?"