有没有办法在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);

有没有更好的方法来做到这一点?

提前致谢。


答案 1

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


答案 2

根据更换件的静态程度,您可以执行

char[] tmp = new char[str.length()];
for( int i=0; i<str.length(); i++ ) {
  char c = str.charAt(i);
  switch( c ) {
    case 's': tmp[i] = 'p'; break;
    case 'p': tmp[i] = 's'; break;
    default: tmp[i] = c; break;
  }
}
str = new String(tmp);

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


推荐