在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
你只需要:
replaceAll("\\s{2,}", " ").trim();
你可以匹配一个或多个空格,用一个空格替换它们,然后在开头和结尾修剪空白(你实际上可以通过先修剪然后匹配来反转正则表达式,就像有人指出的那样)。
要快速测试,请尝试:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
它会返回:
"hello there"
其他回答
试试这个。
示例代码
String str = " hello there ";
System.out.println(str.replaceAll("( +)"," ").trim());
输出
hello there
首先,它将所有空格替换为单个空格。我们必须要做修剪字符串,因为开始的字符串和结束的字符串,它会取代所有的空格,如果字符串有空格在开始的字符串和结束的字符串,所以我们需要修剪它们。然后你会得到你想要的字符串。
在Kotlin中是这样的
val input = "\n\n\n a string with many spaces, \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")
请使用以下代码
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}
流版本,过滤空格和制表符。
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
要消除字符串开头和结尾的空格,请使用String#trim()方法。然后使用你的mytext。replaceAll("()+", " ")。