2 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
Character如果您只想用一個(gè)Character或另一個(gè)替換一個(gè),我已經(jīng)實(shí)施了一個(gè)專(zhuān)門(mén)的解決方案String:
private static Map<Character, Character> REPLACEMENTS = new HashMap<>();
static {
REPLACEMENTS.put('α','a');
REPLACEMENTS.put('β','b');
}
public static String replaceChars(String input) {
StringBuilder sb = new StringBuilder(input.length());
for(int i = 0;i<input.length();++i) {
char currentChar = input.charAt(i);
sb.append(REPLACEMENTS.getOrDefault(currentChar, currentChar));
}
return sb.toString();
}
replace此實(shí)現(xiàn)避免了過(guò)多的字符串復(fù)制/復(fù)雜的正則表達(dá)式,因此與使用or的實(shí)現(xiàn)相比應(yīng)該表現(xiàn)得非常好replaceAll。您也可以將替換更改為String,但替換整個(gè)Strings 而不是Characters更復(fù)雜 - 那么我更喜歡正則表達(dá)式。
編輯:這是針對(duì)上述樣式的整個(gè) s 的解決方案String,但我建議您研究其他解決方案,例如正則表達(dá)式,因?yàn)樗男阅芴卣鞑蝗缟厦娴腃haracter. 此外,它更復(fù)雜且更容易出錯(cuò),但一個(gè)簡(jiǎn)單的測(cè)試表明它可以正常工作。它仍然避免了字符串復(fù)制,因此在性能敏感的場(chǎng)景中它可能更可取。
private static Map<String, String> REPLACEMENTS = new HashMap<>();
static {
REPLACEMENTS.put("aa","AA");
REPLACEMENTS.put("bb","BB");
}
public static String replace(String input) {
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); ++i) {
i += replaceFrom(input, i, sb);
}
return sb.toString();
}
private static int replaceFrom(String input, int startIndex, StringBuilder sb) {
for (Map.Entry<String, String> replacement : REPLACEMENTS.entrySet()) {
String toMatch = replacement.getKey();
if (input.startsWith(toMatch, startIndex)) {
sb.append(replacement.getValue());
//we matched the whole word skip all matched characters
//not just the first
return toMatch.length() - 1;
}
}
sb.append(input.charAt(startIndex));
return 0;
}

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以這樣做。Map 將包含映射,您所要做的就是遍歷映射并調(diào)用replace.
public static void main(String[] args) {
// your input
String old = "something";
// the mappings
Map<Character, Character> mappings = new HashMap<>();
mappings.put('α','a');
// loop through the mappings and perform the action
for (Map.Entry<Character, Character> entry : mappings.entrySet()) {
old = old.replace(entry.getKey(), entry.getValue());
}
}
添加回答
舉報(bào)