在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 blogName = "how to do in java . com";
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");
其他回答
String str = " this is string ";
str = str.replaceAll("\\s+", " ").trim();
我的方法之前,我发现第二个答案使用正则表达式作为一个更好的解决方案。也许有人需要这个代码。
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();
}
你只需要:
replaceAll("\\s{2,}", " ").trim();
你可以匹配一个或多个空格,用一个空格替换它们,然后在开头和结尾修剪空白(你实际上可以通过先修剪然后匹配来反转正则表达式,就像有人指出的那样)。
要快速测试,请尝试:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
它会返回:
"hello there"
试试这个:
String after = before.trim().replaceAll(" +", " ");
另请参阅
String.trim () 返回字符串的副本,省略前导和尾随空格。 regular-expressions.info /重复
没有trim()正则表达式
只用一个replaceAll也可以做到这一点,但这比trim()解决方案可读性差得多。尽管如此,这里提供它只是为了展示regex可以做什么:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
有三名候补:
^_+:字符串开头的任意空格序列 匹配并替换为$1,它捕获空字符串 _+$:字符串结尾的任意空格序列 匹配并替换为$1,它捕获空字符串 (_)+:不匹配上述任何一个空格序列,表示它在中间 匹配并替换为$1,它捕获单个空格
另请参阅
regular-expressions.info /锚
你应该这样做
String mytext = " hello there ";
mytext = mytext.replaceAll("( +)", " ");
把+放在圆括号内。