如何用Java中的相应字符替换特定字符? [英] How to replace specific characters with corresponding characters in java?

查看:42
本文介绍了如何用Java中的相应字符替换特定字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:将所有 ck 替换为 k ,将所有 dd 替换为 wr ,然后所有 f m ,还有10个这样的替代品.我可以用 replace("ck","k").replace("dd","wr")等来完成,但是它接缝很傻并且很慢.java中有没有做类似这样的功能的函数?例如 replace(string,stringArray1,stringArray2);

I want to do something like this: Replace all ck with k and all dd with wr and all f with m and 10 more replacements like this. I can do it with replace("ck","k").replace("dd","wr")and so on, but it seams silly and it is slow. Is there any function in java that does something like this? for example replace(string,stringArray1, stringArray2);

推荐答案

使用这是一种通用的方法:

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+,则第二种方法是:

If you're not using Java 8+, the second method would be:

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 .

See IDEONE for running version.

这篇关于如何用Java中的相应字符替换特定字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆