如果在 Java 中的字符串中有多个空格,如何将它们压缩为单词之间的单个空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4329250/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:57:40  来源:igfitidea点击:

If you have multiple spaces inside a string in Java, how do you condense them into a single space between words?

javastring

提问by Bruce Philby

If a string has multiple spaces between words:

如果字符串在单词之间有多个空格:

The    cat         sat            on           the           mat.

How do you make it a single space?

你如何使它成为一个单一的空间?

The cat sat on the mat.

I tried this but it didn't work:

我试过这个,但没有用:

myText = myText.trim().replace("  ", " ");

回答by Lukas Eder

With a regular expression:

使用正则表达式:

myText.trim().replaceAll("\s+", " ");

This reads: "trim text and then replace all occurrences of one or more than one whitespace character (including tabs, line breaks, etc) by one single whitespace"

内容如下:“修剪文本,然后用一个空格替换所有出现的一个或多个空格字符(包括制表符、换行符等)”

See also java.util.regex.Pattern for more details on Java regular expressions:

有关 Java 正则表达式的更多详细信息,另请参见 java.util.regex.Pattern:

http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

回答by Yuriy

All you need:

一切你需要的:

myText.replaceAll("\s++", " ");

Accordigng to specs of replaceAllmethod of class String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

replaceAll根据类的方法规范Stringhttp: //docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String )

and specs of Patternclass in java(try to ctrl-F for "whitespace", and "++" ): http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

PatternJava 类的规范(尝试按 ctrl-F 表示“空白”和“++”):http: //docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern。 html

In my opinion it's much better to open those pages and take a look by yourself, then just to copy snippet.

在我看来,最好打开这些页面并自己查看,然后复制代码段。