这是im执行的循环。
for(int i=0;i<str.length;i++){
if (str[i]==strFind) {
str[i]=strReplace;
count++;
}
}
问题是,如果句子的最后一个单词在某些测试用例中有句点,而如果我以给定的方式替换句子的最后一个单词,那么在some.And中它就没有句点。我不能保留句号。有没有更简单的解决方案?另外,可以全部替换一个字符串变量(strReplace-user input)吗?
发布于 2020-07-06 10:28:20
您可以在您的场景中使用java的内置字符串函数replace
。
int getReplacementCount(String sentence,String searchWord, String replacement){
int count = 0;
while(true){
String replacedSentence = sentence.replace(searchWord,replacement);
if(replacedSentence.equals(sentence){
return count;
else {
count++;
sentence = replacedSentence;
}
}
}
发布于 2020-07-06 10:32:30
也许这里的问题是,您想要替换字符串,但您只是观察并迭代字符串的单个字符。您可以使用Apache Commons lang.
StringUtils.replace(text, searchString, replacement)
发布于 2020-07-06 10:44:54
这可以通过java中的内置库来实现。
您可以简单地使用:
String str1 = "Hello world";
//usage: str1.replace(word_or_character to replace, replacement)
str1 = str1.replace(" ", "")
System.out.println(str1)
输出:
Helloworld
https://stackoverflow.com/questions/62753855
复制相似问题