我正在尝试制定一种“修复”句子的方法。因此,例如,如果句子是“the Cookie is BROwN”,它将返回“The cookie is Brown.”。现在我正在尝试研究“空间修复器”部分,其中多个空间将被分析并变成单个空间。这是我到目前为止的代码。有人可以告诉我如何修复空间并消除不必要的空间吗?我知道它还没有完成。我目前只是想修复这些空间。下面是我的代码。
public static String sentenceRepair(String sentence){
String finale="";
for (int x=0;x<sentence.length();x++){
char a= sentence.charAt(x);
if (sentence.charAt(x)==' '){ //SPACE CHECKER!!
if((x!=0&&x!=sentence.length())&&(sentence.charAt(x-1)==' '||sentence.charAt(x+1)==' ')){
sentence.charAt(x)="";
}
}
}
return finale;
}
最佳答案
我会使用正则表达式:
public static String sentenceRepair(String sentence){
return sentence.replaceAll(" +", " ");
}
关于java - 如何去掉字符串中的多个空格并保留一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204527/