在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
要消除字符串开头和结尾的空格,请使用String#trim()方法。然后使用你的mytext。replaceAll("()+", " ")。
其他回答
"[ ]{2,}"
这将匹配多个空格。
String mytext = " hello there ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);
输出:
hello there
我的方法之前,我发现第二个答案使用正则表达式作为一个更好的解决方案。也许有人需要这个代码。
private String replaceMultipleSpacesFromString(String s){
if(s.length() == 0 ) return "";
int timesSpace = 0;
String res = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' '){
timesSpace++;
if(timesSpace < 2)
res += c;
}else{
res += c;
timesSpace = 0;
}
}
return res.trim();
}
String str = " hello world"
首先减少空间
str = str.trim().replaceAll(" +", " ");
第一个字母大写,其他字母小写
str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
看到String.replaceAll。
使用正则表达式“\s”并替换为“”。
然后使用String.trim。
如果你已经在你的项目中使用了Guava(19+节),你可能想要使用这个:
CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');
或者,如果你需要删除空格符号(或U+0020,查看更多空白),使用:
CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');