用更简洁的字符串编码方式替换多个 replaceAll

我需要replaceAll在一个字符串中执行多个命令,我想知道是否有一种干净的方法可以做到这一点。目前是这样的:

newString = oldString.replaceAll("α","a").replaceAll("β","b").replace("c","σ") /* This goes on for over 60 replacements*/;



慕慕森
浏览 215回答 2
2回答

白板的微信

Character如果您只想用一个Character或另一个替换一个,我已经实施了一个专门的解决方案String:private static Map<Character, Character> REPLACEMENTS = new HashMap<>();static {&nbsp; &nbsp; REPLACEMENTS.put('α','a');&nbsp; &nbsp; REPLACEMENTS.put('β','b');}public static String replaceChars(String input) {&nbsp; &nbsp; StringBuilder sb = new StringBuilder(input.length());&nbsp; &nbsp; for(int i = 0;i<input.length();++i) {&nbsp; &nbsp; &nbsp; &nbsp; char currentChar = input.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; sb.append(REPLACEMENTS.getOrDefault(currentChar, currentChar));&nbsp; &nbsp; }&nbsp; &nbsp; return sb.toString();}replace此实现避免了过多的字符串复制/复杂的正则表达式,因此与使用or的实现相比应该表现得非常好replaceAll。您也可以将替换更改为String,但替换整个Strings 而不是Characters更复杂 - 那么我更喜欢正则表达式。编辑:这是针对上述样式的整个 s 的解决方案String,但我建议您研究其他解决方案,例如正则表达式,因为它的性能特征不如上面的Character. 此外,它更复杂且更容易出错,但一个简单的测试表明它可以正常工作。它仍然避免了字符串复制,因此在性能敏感的场景中它可能更可取。private static Map<String, String> REPLACEMENTS = new HashMap<>();static {&nbsp; &nbsp; REPLACEMENTS.put("aa","AA");&nbsp; &nbsp; REPLACEMENTS.put("bb","BB");}&nbsp; &nbsp; public static String replace(String input) {&nbsp; &nbsp; StringBuilder sb = new StringBuilder(input.length());&nbsp; &nbsp; for (int i = 0; i < input.length(); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; i += replaceFrom(input, i, sb);&nbsp; &nbsp; }&nbsp; &nbsp; return sb.toString();}private static int replaceFrom(String input, int startIndex, StringBuilder sb) {&nbsp; &nbsp; for (Map.Entry<String, String> replacement : REPLACEMENTS.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; String toMatch = replacement.getKey();&nbsp; &nbsp; &nbsp; &nbsp; if (input.startsWith(toMatch, startIndex)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(replacement.getValue());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //we matched the whole word skip all matched characters&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //not just the first&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return toMatch.length() - 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; sb.append(input.charAt(startIndex));&nbsp; &nbsp; return 0;}

www说

你可以这样做。Map 将包含映射,您所要做的就是遍历映射并调用replace.public static void main(String[] args) {&nbsp; &nbsp; // your input&nbsp; &nbsp; String old = "something";&nbsp; &nbsp; // the mappings&nbsp; &nbsp; Map<Character, Character> mappings = new HashMap<>();&nbsp; &nbsp; mappings.put('α','a');&nbsp; &nbsp; // loop through the mappings and perform the action&nbsp; &nbsp; for (Map.Entry<Character, Character> entry : mappings.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; old = old.replace(entry.getKey(), entry.getValue());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java