我想知道
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);
有没有更好的方法来做到这一点?
提前致谢.