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

Lim*_*Luo 14 java tr str-replace

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

#shebang and pragmas snipped...
my $str = "mississippi";
$str =~ tr/sp/ps/;  # $str = "mippippissi"
print $str;
Run Code Online (Sandbox Code Playgroud)

我能想到用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);
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

提前致谢.

Dav*_*ton 5

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