【问题标题】:How to remove spaces in between the String如何删除字符串之间的空格
【发布时间】:2013-09-23 02:30:22
【问题描述】:

我有下面的字符串

  string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
  string = str.replace("\\s","").trim();

哪个返回

  str = "Book Your Domain And Get     Online Today."

但我们想要的是

  str = "Book Your Domain And Get Online Today."

我尝试了许多正则表达式,也用谷歌搜索过,但没有运气。并没有找到相关问题,请帮助,非常感谢提前

【问题讨论】:

  • 所有换行符是怎么回事?

标签: java regex string


【解决方案1】:

使用\\s+ 而不是\\s,因为您的输入中有两个或更多连续的空格。

string = str.replaceAll("\\s+"," ")

【讨论】:

  • @JayakrishnanPm 这将删除所有空格,而不是用单个空格替换多个连续空格。
【解决方案2】:

您可以使用replaceAll,它将正则表达式作为参数。似乎您想用一个空格替换多个空格。你可以这样做:

string = str.replaceAll("\\s{2,}"," ");

它将用一个空格替换 2 个或更多连续的空格。

【讨论】:

    【解决方案3】:

    先去掉多个空格:

    String after = before.trim().replaceAll(" +", " ");
    

    【讨论】:

      【解决方案4】:

      如果您只想删除两个单词或字符之间的空格,而不是字符串末尾的空格 那么这里是 我用过的正则表达式,

              String s = "   N    OR  15  2    ";
      
          Pattern pattern = Pattern.compile("[a-zA-Z0-9]\\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE); 
      
          Matcher m = pattern.matcher(s);
      
              while(m.find()){
              String replacestr = "";
      
      
              int i = m.start();
                  while(i<m.end()){
                      replacestr = replacestr + s.charAt(i);
                      i++;
                  }
      
                  m = pattern.matcher(s);
              }
      
              System.out.println(s);
      

      它只会删除字符或单词之间的空格而不是末尾的空格 输出是

      NOR152

      【讨论】:

        【解决方案5】:

        例如。删除字符串中单词之间的空格:

        String example = "Interactive Resource";

        System.out.println("Without space string: "+ example.replaceAll("\\s",""));

        输出: Without space string: InteractiveResource

        【讨论】:

          【解决方案6】:

          如果要打印不带空格的字符串,只需在打印函数中添加参数 sep='',因为该参数的默认值为“”。

          【讨论】:

            【解决方案7】:
            //user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
            //output: 1234 
            a.replaceAll("\\s", "")
            

            【讨论】:

              【解决方案8】:

              字符串 s2="1 2 3 4 5"; String after=s2.replace(" ", "");

              这对我有用

              【讨论】:

              • 其他答案已经涵盖了这一点。
              猜你喜欢
              • 2015-02-12
              • 2023-01-31
              • 2015-03-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-05-18
              • 2015-04-27
              • 1970-01-01
              相关资源
              最近更新 更多