有没有办法在java中使用tr ///(或等效)?

我想知道Java中是否存在等价于tr ///(在Perl中使用的)。 例如,如果我想用“密西西比”中的“p”替换所有“s”,反之亦然,我可以在Perl中写

#shebang and pragmas snipped... my $str = "mississippi"; $str =~ tr/sp/ps/; # $str = "mippippissi" print $str; 

我能想到用Java做的唯一方法是使用带有String.replace()方法的虚拟字符,即

 String str = "mississippi"; str = str.replace('s', '#'); // # is just a dummy character to make sure // any original 's' doesn't get switched to a 'p' // and back to an 's' with the next line of code // str = "mi##i##ippi" str = str.replace('p', 's'); // str = "mi##i##issi" str = str.replace('#', 'p'); // str = "mippippissi" System.out.println(str); 

有一个更好的方法吗?

提前致谢。

Commons的replaceChars可能是你最好的选择。 AFAIK在JDK中没有替代品(ar ar)。

根据您的替换静态程度,您可以这样做

 char[] tmp = new char[str.length()]; for( int i=0; i 

如果替换需要在运行时变化,您可以使用表查找替换开关(如果您知道需要替换的所有代码点都属于有限范围,例如ASCII),或者,如果其他所有操作都失败,则使用散列映射从CharacterCharacter

正如@Dave已经指出最接近的替代品是

Apache Commons StringUtils.replaceChars(String str,String searchChars,String replaceChars)

摘录描述:

 ... StringUtils.replaceChars(null, *, *) = null StringUtils.replaceChars("", *, *) = "" StringUtils.replaceChars("abc", null, *) = "abc" StringUtils.replaceChars("abc", "", *) = "abc" StringUtils.replaceChars("abc", "b", null) = "ac" StringUtils.replaceChars("abc", "b", "") = "ac" StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya" StringUtils.replaceChars("abcba", "bc", "y") = "ayya" StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya" ...