有没有办法在java中使用 tr/// (或等效的)?
我想知道 Java 中是否有与 tr/// (如 Perl 中使用的)等效的东西。例如,如果我想用“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);
是否有更好的方法来做到这一点?
提前致谢。
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;
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);
Is there a better way to do this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
公共资源的 replaceChars 可能是您最好的选择。 AFAIK JDK 中没有替代品 (ar ar)。
Commons' replaceChars may be your best bet. AFAIK there's no replacement (ar ar) in the JDK.
根据替换的静态程度,您可以执行
如果替换需要在运行时变化,您可以使用表查找来替换开关(如果您知道需要替换的所有代码点都在有限范围内,例如 ASCII ),或者,如果其他一切都失败,则使用从
Character
到Character
的哈希映射。Depending on how static your replacement is, you could do
If the replacements need to vary at runtime, you could replace the switch with a table lookup (if you know that all the codepoints you need to replace fall into a limited range, such as ASCII), or, if everything else fails, a hashmap from
Character
toCharacter
.正如 @Dave 已经指出的,最接近的替代品是
Apache Commons StringUtils.replaceChars(String str, String searchChars, String ReplaceChars)
描述摘录:
As @Dave already pointed out the closest replacement is
Apache Commons StringUtils.replaceChars(String str, String searchChars, String replaceChars)
Excerpt of the description: