【问题标题】:How to get rid of multiple spaces in a string and leave one如何摆脱字符串中的多个空格并留下一个
【发布时间】:2018-05-06 21:06:54
【问题描述】:

我正在尝试制作一种“修复”句子的方法。因此,例如,如果句子是“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;
}

【问题讨论】:

标签: java string spaces


【解决方案1】:

我会使用正则表达式:

public static String sentenceRepair(String sentence){
  return sentence.replaceAll(" +", " ");
}

【讨论】:

    【解决方案2】:

    你的版本比它需要的复杂得多

    String str = " hello     there   ";
    str = str.replaceAll("( +)"," ").trim());
    

    此代码将所有多个空格替换为一个空格,并使用正则表达式“代码”删除字符串前后的每个空格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2020-08-18
      • 1970-01-01
      相关资源
      最近更新 更多