Java中的字符串替换 [英] String replace in Java
问题描述
我目前有一个包含字符A,B和C的字符串,例如字符串看起来像
I currently have a string which contains the characters A, B and C for example the string looks like
"A some other random stuff B C"
其他随机的东西不包含A,B或CI想要替换A,B& C分别带有'A','B'和'C',目前我正在做的最好的方法是:
the other random stuff doesn't contain A, B or C I want to replace the A, B & C with 'A', 'B' and 'C' respectively what's the best way to do that currently I'm doing:
String.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'")
推荐答案
如果A,B和C是那些确切的单个字符,则cletus'的答案正常,但如果它们可能是更长的字符串,你只是将它们称为A,B和C。如果它们是更长的字符串你需要做:
cletus' answer works fine if A, B and C are those exact single characters, but not if they could be longer strings and you just called them A, B and C for example purposes. If they are longer strings you need to do:
String input = "FOO some other random stuff BAR BAZ";
String output = input.replaceAll("FOO|BAR|BAZ", "'$0'");
您还需要转义FOO,BAR和BAZ中的任何特殊字符,以便它们不被解释作为特殊的正则表达式符号。
You will also need to escape any special characters in FOO, BAR and BAZ so that they are not interpreted as special regular expression symbols.
这篇关于Java中的字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!