Java字符串里如何用单个空格替换2个或更多的空格,并删除前面和后面的空格| Java Debug 笔记

102 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接

问题:Java字符串里如何用单个空格替换2个或更多的空格,并删除前面和后面的空格

寻找Java中快速、简单的方法来改变这个字符串 " hello there " 变成这样

"hello there" where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.

Something like this gets me partly there

在这里我用一个空格替换所有这些多个空格,除了我也想在字符串开始的一个或多个空格消失。

下面的让我在一定程度上明白了

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

但不是非常完全

回答

You just need a: 你只需要:

replaceAll("\\s{2,}", " ").trim();

匹配一个或多个空格,然后用一个空格替换它们,然后在开头和结尾处trim 空格(有人指出,实际上可以通过先修剪再匹配来使正则表达式更快)。

要快速测试这一点,请尝试:

System.out.println(new String(" hello     there   ").trim().replaceAll("\\s{2,}", " "));

它会返回

"hello there"

回答二

下面的代码将压缩单词之间的空格并删除字符串开头和结尾的空格

String input = "\n\n\n  a     string with     many    spaces,    \n"+
               " a \t tab and a newline\n\n";
String output = input.trim().replaceAll("\\s+", " ");
System.out.println(output);

这将输出一个包含许多空格、制表符和换行符的字符串

请注意,任何不可打印的字符,包括空格、制表符和换行符都会被压缩或删除

有关更多信息,请参阅相关文档:

  • String#trim() method
  • String#replaceAll(String regex, String replacement) method
  • For information about Java's regular expression implementation see the documentation of the Pattern class

文章翻译自Stack Overflow:stackoverflow.com/questions/2…