【问题标题】:String whitespace clean up that is not trim [duplicate]字符串空白清理不是修剪[重复]
【发布时间】:2014-11-28 13:50:58
【问题描述】:

所以我一直在看这里,我可以找到很多解决方案,它们要么完全删除所有空白,要么只删除空格,或者只删除标签。基本上我需要/想要的是一种获取字符串的方法,然后将所有双空格+或制表符转换为单个空格。即

String temp = "This is   a     test        for strings";
String result = "This is a test for strings";

有什么想法吗?可能的 java 库方法?

【问题讨论】:

    标签: java regex string removing-whitespace


    【解决方案1】:

    使用String.replaceAll:

    String result = temp.replaceAll("\\s+", " ");
    

    其中\\s+ 代表多个空格字符。

    【讨论】:

    • 两位谢谢! 1. 谢谢,老实说,这正是我想要的。 2.不开玩笑
    【解决方案2】:

    您可以将regExp#replaceAll 方法一起使用,但您可以首先使用 trim 删除前导和尾随空格。

        String temp = "This is   a     test        for strings";
        String result = temp.replaceAll("\\s+", " ");
    

    这里的\\s+regExp,意思是一个或多个空格将被replaceAll 方法替换为单个空格。

    【讨论】:

      【解决方案3】:

      试试这个:

      String temp = "This is   a     test        for strings";
      String result = temp.replaceAll("\\s+", " "));
      

      【讨论】:

        猜你喜欢
        • 2016-06-23
        • 2012-03-21
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多