在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
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;
}
}
}
上面的解决方案是复杂度为O(n)的算法,没有使用任何java函数。
其他回答
如果你已经在你的项目中使用了Guava(19+节),你可能想要使用这个:
CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');
或者,如果你需要删除空格符号(或U+0020,查看更多空白),使用:
CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');
流版本,过滤空格和制表符。
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
在Kotlin中是这样的
val input = "\n\n\n a string with many spaces, \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")
要消除字符串开头和结尾的空格,请使用String#trim()方法。然后使用你的mytext。replaceAll("()+", " ")。
请使用以下代码
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());
}
}