在Java中寻找快速、简单的方法来更改此字符串

" hello     there   "

变成了这样的东西

"hello there"

在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。

像这样的事情能让我在一定程度上做到

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

但事实并非如此。


当前回答

这对我来说非常有效:sValue = sValue.trim()。replaceAll("\\s+", " ");

其他回答

你应该这样做

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

把+放在圆括号内。

String str = " hello world"

首先减少空间

str = str.trim().replaceAll(" +", " ");

第一个字母大写,其他字母小写

str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();

你只需要:

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

你可以匹配一个或多个空格,用一个空格替换它们,然后在开头和结尾修剪空白(你实际上可以通过先修剪然后匹配来反转正则表达式,就像有人指出的那样)。

要快速测试,请尝试:

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

它会返回:

"hello there"

使用Apache commons StringUtils。normalizeSpace(String str)方法。点击这里查看文档

削减()

只删除开头和结尾空格。

从Java文档, 返回值为此字符串的字符串,删除前导和尾部的任何空格。

System.out.println(" D ev  Dum my ".trim());

“D ev House my”

replace(), replaceAll()

替换单词中的所有空字符串,

System.out.println(" D ev  Dum my ".replace(" ",""));

System.out.println(" D ev  Dum my ".replaceAll(" ",""));

System.out.println(" D ev  Dum my ".replaceAll("\\s+",""));

输出:

"DevDummy"

"DevDummy"

"DevDummy"

注意:“\s+”为类似空格字符的正则表达式。

参考资料:https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html