How to replace specific characters with corresponding characters in java? [duplicate]

你离开我真会死。 提交于 2020-01-11 11:36:01

问题


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


回答1:


Use an appendReplacement loop.

Here is a general purpose way to do it:

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("|"));
}

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();
}

Test code

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

See IDEONE for running version.




回答2:


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);
    }
}

The replaceAll() method was borrowed from this Jon Skeet's answer

Alternative to replaceAll() int his example is to use apache commons library, there is StrBuilder class which provides replaceAll() method. see this answer



来源:https://stackoverflow.com/questions/46133476/how-to-replace-specific-characters-with-corresponding-characters-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!