如何用java中的相应字符替换特定字符?

hsvhsicv  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(333)

这个问题在这里已经有答案了

使用替换字符串中多个单词的最有效方法[重复](4个答案)
三年前关门了。
我想这样做:全部替换 ckk 以及所有 ddwr 以及所有 fm 还有10个这样的替代品。我可以和你一起做 replace("ck","k").replace("dd","wr") 以此类推,但这是愚蠢的,它是缓慢的。java中有这样的函数吗?例如 replace(string,stringArray1, stringArray2);

mv1qrgav

mv1qrgav1#

Map<String, String> replacementMap = new HashMap<String, String>();
replacementMap.put("ck", "k");
replacementMap.put("dd", "wr");
replacementMap.put("f", "m");
// ...

String resultStr = "Abck fdddk wr fmck"; // whatever string to process
StringBuilder builder = new StringBuilder(resultStr); // wrap it in builder

Iterator<String> iterator = replacementMap.keySet().iterator();
while (iterator.hasNext()) {
    String strToReplace = iterator.next();
    replaceAll(builder, strToReplace, replacementMap.get(strToReplace));
}
System.out.println("Result is: " + builder.toString());

public static void replaceAll(StringBuilder builder, String from, String to) {
    int index = builder.indexOf(from);
    while (index != -1) {
        builder.replace(index, index + from.length(), to);
        index += to.length(); // Move to the end of the replacement
        index = builder.indexOf(from, index);
    }
}

replaceall()方法是从jon skeet的答案中借用的
replaceall()int的另一种方法是使用ApacheCommons库,strbuilder类提供replaceall()方法。看到这个答案了吗

goqiplq2

goqiplq22#

使用 appendReplacement 循环。
以下是一种通用方法:

private static String replace(String input, Map<String, String> mappings) {
    StringBuffer buf = new StringBuffer();
    Matcher m = Pattern.compile(toRegex(mappings.keySet())).matcher(input);
    while (m.find())
        m.appendReplacement(buf, Matcher.quoteReplacement(mappings.get(m.group())));
    return m.appendTail(buf).toString();
}
private static String toRegex(Collection<String> keys) {
    return keys.stream().map(Pattern::quote).collect(Collectors.joining("|"));
}

如果您不使用java 8+,第二种方法是:

private static String toRegex(Collection<String> keys) {
    StringBuilder regex = new StringBuilder();
    for (String key : keys) {
        if (regex.length() != 0)
            regex.append("|");
        regex.append(Pattern.quote(key));
    }
    return regex.toString();
}

测试代码

Map<String, String> mappings = new HashMap<>();
mappings.put("ck","k");
mappings.put("dd","wr");
mappings.put("f", "m");
System.out.println(replace("odd flock", mappings)); // prints: owr mlok

运行版本见ideone。

相关问题