Java如何用字符串中的单个空格替换2个或更多空格并删除前导和尾随空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2932392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces
提问by Nessa
Looking for quick, simple way in Java to change this string
在 Java 中寻找快速、简单的方法来更改此字符串
" hello there "
to something that looks like this
看起来像这样的东西
"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("( )+", " ");
but not quite.
但不完全是。
回答by Eyal Schneider
You can first use String.trim()
, and then apply the regex replace command on the result.
您可以先使用String.trim()
,然后对结果应用正则表达式替换命令。
回答by Zak
See String.replaceAll
.
见String.replaceAll
。
Use the regex "\s"
and replace with " "
.
使用正则表达式"\s"
并替换为" "
.
Then use String.trim
.
然后使用String.trim
.
回答by folone
To eliminate spaces at the beginning and at the end of the String, use String#trim()
method. And then use your mytext.replaceAll("( )+", " ")
.
要消除字符串开头和结尾的空格,请使用String#trim()
方法。然后使用您的mytext.replaceAll("( )+", " ")
.
回答by polygenelubricants
Try this:
尝试这个:
String after = before.trim().replaceAll(" +", " ");
See also
也可以看看
String.trim()
- Returns a copy of the string, with leading and trailing whitespace omitted.
- regular-expressions.info/Repetition
String.trim()
- 返回字符串的副本,省略前导和尾随空格。
- 正则表达式.info/Repetition
No trim()
regex
没有trim()
正则表达式
It's also possible to do this with just one replaceAll
, but this is much less readable than the trim()
solution. Nonetheless, it's provided here just to show what regex can do:
也可以只用一个 来做到这一点replaceAll
,但这比trim()
解决方案可读性要差得多。尽管如此,这里提供它只是为了展示正则表达式可以做什么:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "")
);
}
There are 3 alternates:
有3个备选:
^_+
: any sequence of spaces at the beginning of the string- Match and replace with
$1
, which captures the empty string
- Match and replace with
_+$
: any sequence of spaces at the end of the string- Match and replace with
$1
, which captures the empty string
- Match and replace with
(_)+
: any sequence of spaces that matches none of the above, meaning it's in the middle- Match and replace with
$1
, which captures a single space
- Match and replace with
^_+
: 字符串开头的任何空格序列- 匹配并替换为
$1
,捕获空字符串
- 匹配并替换为
_+$
: 字符串末尾的任何空格序列- 匹配并替换为
$1
,捕获空字符串
- 匹配并替换为
(_)+
: 任何不匹配上述任何一个的空格序列,这意味着它在中间- 匹配并替换为
$1
,捕获单个空格
- 匹配并替换为
See also
也可以看看
回答by Mr_Hmp
This worked for me
这对我有用
scan= filter(scan, " [\s]+", " ");
scan= sac.trim();
where filter is following function and scan is the input string:
其中 filter 是以下函数, scan 是输入字符串:
public String filter(String scan, String regex, String replace) {
StringBuffer sb = new StringBuffer();
Pattern pt = Pattern.compile(regex);
Matcher m = pt.matcher(scan);
while (m.find()) {
m.appendReplacement(sb, replace);
}
m.appendTail(sb);
return sb.toString();
}
回答by sarah.ferguson
You just need a:
你只需要一个:
replaceAll("\s{2,}", " ").trim();
where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
在其中匹配一个或多个空格并用单个空格替换它们,然后在开头和结尾修剪空格(您实际上可以通过先修剪然后匹配来反转,以使正则表达式更快,正如有人指出的那样)。
To test this out quickly try:
要快速测试这一点,请尝试:
System.out.println(new String(" hello there ").trim().replaceAll("\s{2,}", " "));
and it will return:
它会返回:
"hello there"
回答by KhaledMohamedP
String str = " hello world"
reduce spaces first
先减少空格
str = str.trim().replaceAll(" +", " ");
capitalize the first letter and lowercase everything else
大写第一个字母,小写其他所有字母
str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
回答by Avinash Raj
You could use lookarounds also.
您也可以使用环视。
test.replaceAll("^ +| +$|(?<= ) ", "");
OR
或者
test.replaceAll("^ +| +$| (?= )", "")
<space>(?= )
matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.
<space>(?= )
匹配后跟另一个空格字符的空格字符。因此,在连续空格中,它将匹配除最后一个空格之外的所有空格,因为它后面没有空格字符。这会在删除操作后为连续空格留下一个空格。
Example:
例子:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$| (?= )", "")
);
}
回答by devmohd
public class RemoveExtraSpacesEfficient {
public static void main(String[] args) {
String s = "my name is mr space ";
char[] charArray = s.toCharArray();
char prev = s.charAt(0);
for (int i = 0; i < charArray.length; i++) {
char cur = charArray[i];
if (cur == ' ' && prev == ' ') {
} else {
System.out.print(cur);
}
prev = cur;
}
}
}
The above solution is the algorithm with the complexity of O(n) without using any java function.
上面的解决方案是不使用任何java函数的复杂度为O(n)的算法。