有没有办法在java中使用tr///(或等效)?
2022-09-03 08:02:02
我想知道Java中是否有与tr / / /(在Perl中使用的)等效的。例如,如果我想将所有“s”替换为“mississippi”中的“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);
有没有更好的方法来做到这一点?
提前致谢。