Home  >  Article  >  Java  >  How to Efficiently Replace Multiple Substrings in a Java String?

How to Efficiently Replace Multiple Substrings in a Java String?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 23:21:30268browse

How to Efficiently Replace Multiple Substrings in a Java String?

Efficient String Substitution in Java

Replacing multiple substrings in a string efficiently is a common task in programming. While the brute-force approach of using String.replace() for each substitution is straightforward, it can be inefficient, especially for large strings or when dealing with many replacements.

Replacing Substrings Using Regular Expressions

A more efficient solution involves using regular expressions. By compiling a pattern that matches all the desired substring replacements, you can replace multiple substrings at once.

Consider the following code example, which replaces tokens from a map within a template string using regular expressions:

<code class="java">import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

...

// Tokens to replace
Map<String, String> tokens = new HashMap<>();
tokens.put("cat", "Garfield");
tokens.put("beverage", "coffee");

// Template string with tokens
String template = "%cat% really needs some %beverage%.";

// Create pattern to match tokens
String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(template);

// Replace tokens using Matcher
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
}
matcher.appendTail(sb);

System.out.println(sb.toString()); // Prints the replaced string</code>

By using regular expressions, you can significantly improve the efficiency of multiple substring replacements, especially for large or complex input strings.

The above is the detailed content of How to Efficiently Replace Multiple Substrings in a Java String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn