本文介绍了有没有一种方法可以在Java中使用tr///(或等效方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Java中是否有等效于tr///(在Perl中使用的).例如,如果我想用"mississippi"中的所有"s"替换为"p",反之亦然,那么我可以在Perl中编写

I would like to know if there is an equivalent to tr/// (as used in Perl) in Java. For example, if I wanted to replace all "s"s with "p"s in "mississippi" and vice versa, I could, in Perl, write

#shebang and pragmas snipped...
my $str = "mississippi";
$str =~ tr/sp/ps/;  # $str = "mippippissi"
print $str;

在Java中我想到的唯一方法是在String.replace()方法中使用伪字符,即

The only way I can think of to do it in Java is to use a dummy character with the String.replace() method, i.e.

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);

有更好的方法吗?

谢谢.

推荐答案

常见问题 replaceChars 可能是您最好的选择. AFAIK在JDK中没有替代品(ar ar).

Commons' replaceChars may be your best bet. AFAIK there's no replacement (ar ar) in the JDK.

这篇关于有没有一种方法可以在Java中使用tr///(或等效方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:45