Java 如何用字符串替换下划线?
如何在java中用字符串替换下划线?我试着用替换法,但没用Java 如何用字符串替换下划线?,java,Java,如何在java中用字符串替换下划线?我试着用替换法,但没用 public class HelloWorld{ public static void main(String []args){ String value = "Once upon a time there _________ man called Damocles"; String result = value.replace('_', 'michief');
public class HelloWorld{
public static void main(String []args){
String value = "Once upon a time there _________ man called Damocles";
String result = value.replace('_', 'michief');
System.out.println(result);
}
}
首先,Java中的
字符串需要用双引号括起来。因此,您需要使用“
和“恶作剧”
而不是“
和“恶作剧”
其次,replace(“513;”,“miskief”)
将用单词“miskief”替换所有出现的下划线。因为您的输入字符串有多个下划线,所以您会得到类似“mischiefmischiefmischief”的结果
要解决此问题,请使用replaceFirst
仅替换第一个下划线,然后使用replace
删除所有其他下划线:
publicstaticvoidmain(字符串[]args){
String value=“从前有一个叫达摩克利斯的人”;
String result=value.replaceFirst(“_”,“michief”);//将第一个下划线替换为“miskief”
result=result.replace(““,”);//通过将其他下划线替换为空字符串来删除它们
系统输出打印项次(结果);
}
可以替换模式:
String result=value.replaceFirst(“+”,“michief”);
正则表达式与一个或多个连续下划线匹配
(正如其他人已经指出的,对于Java中的字符串,您还需要使用“…”
而不是“…”
)如果您正在寻找一种幕后方法来了解不使用正则表达式(尽管不是最佳解决方案)会发生什么,请查看以下内容:
String originalText = "Once upon a time there _________ man called Damocles";
String wordToReplace = "mischief";
// get the first and last index of the underscore substring sequence
// assuming that there are no other characters in between underscores
int firstIndexOfUnderscore = originalText.indexOf("_");
int lastIndexOfUnderscore = originalText.lastIndexOf("_", firstIndexOfUnderscore);
// get the full underscore substring
String underscoreSubstring = originalText.substring(firstIndexOfUnderscore, lastIndexOfUnderscore + 1);
// replace the full underescore substring with the word to replace
originalText.replace(underscoreSubstring, wordToReplace)
尝试用双引号替换单引号。(删除我的评论,因为答案已经涵盖了它,因为我在正则表达式上犯了一个愚蠢的错误,现在编辑已经太晚了)这是工作的两倍replaceFirst
适用于正则表达式。是的,但我要找一个更简单的解释,OP在这里理解它而不是效率。显然,由于OP对字符串使用单引号,因此它们也是一个初学者。替换(“\u“,”)
将删除所有\u
,而不管它们的位置如何,这可能不是OP想要的。例如,在Foo\uuuuuubar\uuuuuuuubaz
的情况下,OP可能只想将单词放在第一个\uuuuuuuuu
中,而不删除第二个。因此,replaceFirst(“+”,“michief”)
可能是更安全的选择。
String originalText = "Once upon a time there _________ man called Damocles";
String wordToReplace = "mischief";
// get the first and last index of the underscore substring sequence
// assuming that there are no other characters in between underscores
int firstIndexOfUnderscore = originalText.indexOf("_");
int lastIndexOfUnderscore = originalText.lastIndexOf("_", firstIndexOfUnderscore);
// get the full underscore substring
String underscoreSubstring = originalText.substring(firstIndexOfUnderscore, lastIndexOfUnderscore + 1);
// replace the full underescore substring with the word to replace
originalText.replace(underscoreSubstring, wordToReplace)