我想知道在Java中是否有等價於tr ///(在Perl中使用)。例如,如果我想全部替換「的」 s的「P」 S在「密西西比」,反之亦然,我可以,在Perl,寫有沒有辦法在java中使用tr ///(或等效)?
#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);
有沒有更好的方式來做到這一點?
在此先感謝。
這篇文章可能有助於http://stackoverflow.com/questions/ 3254358 /替換炭到炭在-A-串 –