Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

java - 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 substring of a string at one time? or is there a better way to replace string?

Added:

I hope to find a way which can replace substring quickly!

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

   s=s.replace("%ToolBar%","Edit ToolBar");
   s=s.replace("%Content%","made by Paul");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

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

StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s);
while (m.find()) {
    if (m.start(1) != -1)
        m.appendReplacement(buf, "Edit ToolBar");
    else if (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...