java:从 StringBuilder 中删除所有空格的最有效方法是什么

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

java: what's the most efficient way to remove all blank space from a StringBuilder

java

提问by remy

I implement it by the following code, but I don't know whether there's a more efficient way to remove all blank spaces from a StringBuilder

我是通过下面的代码实现的,但是不知道有没有更有效的方法可以从StringBuilder中删除所有空格

private static StringBuilder removeBlankSpace(StringBuilder sb){
    for(int i=0;i<sb.length();++i){
        if(Character.isWhitespace(sb.charAt(i))){
            sb.deleteCharAt(i);
                            i--;
        }
    }
    return sb;
}

回答by Keith Randall

You shouldn't call deletemore than once - simply move each character down to its final location and then delete the range at the end.

您不应delete多次调用- 只需将每个字符向下移动到其最终位置,然后在最后删除范围。

static void removeBlankSpace(StringBuilder sb) {
  int j = 0;
  for(int i = 0; i < sb.length; i++) {
    if (!Character.isWhitespace(sb.charAt(i))) {
       sb.setCharAt(j++, sb.charAt(i));
    }
  }
  sb.delete(j, sb.length);
}

回答by Jon Skeet

EDIT: Leaving this answer in for posterity, but Keith Randall's O(n) solutionis much nicer.

编辑:将此答案留给后人,但 Keith Randall 的 O(n) 解决方案要好得多。

You may find it's more efficient to work from the far end - as that way by the time you remove earlycharacters, you won't be copying whitespace from later.

您可能会发现从远端工作会更有效率 - 这样当您删除早期字符时,您就不会从后面复制空格。

Also, if your data tends to have multiple whitespace characters together, you may wish to spot that and call deleterather than deleteCharAt. So something like:

此外,如果您的数据往往有多个空白字符,您可能希望发现它并调用delete而不是deleteCharAt. 所以像:

private static StringBuilder removeBlankSpace(StringBuilder sb) {
    int currentEnd = -1;
    for(int i = sb.length() - 1; i >= 0; i--) {
        if (Character.isWhitespace(sb.charAt(i))) {
            if (currentEnd == -1) {
                currentEnd = i + 1;
            }
        } else {
            // Moved from whitespace to non-whitespace
            if (currentEnd != -1) {
                sb.delete(i + 1, currentEnd);
                currentEnd = -1;
            }
        }
    }
    // All leading whitespace
    if (currentEnd != -1) {
        sb.delete(0, currentEnd);
    }
    return sb;
}

回答by aviad

How about the following (assuming that you have your StringBuilder sbinitialized):

以下如何(假设您已StringBuilder sb初始化):

sb = new StringBuilder(sb.toString().replaceAll("\s", ""));

回答by sivaram Nulakani

Code to Remove Leading & Trailing spaces of a String

删除字符串前导和尾随空格的代码

 int i = 0;
 int j = 0;

 for (; i < whiteSpcaTest.length();) {
   i = 0;
   if (Character.isWhitespace(whiteSpcaTest.charAt(i))) {
     whiteSpcaTest.deleteCharAt(i);

   } else {
     break;
   }
 }
 for (; j >= 0;) {
   j = whiteSpcaTest.length() - 1;
   if (Character.isWhitespace(whiteSpcaTest.charAt(j))) {
     whiteSpcaTest.deleteCharAt(j);

   } else {
     break;
   }

 }

回答by Sohrab

The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. For example:

java string trim() 方法消除了前导和尾随空格。空格字符的 unicode 值为 '\u0020'。java 字符串中的trim() 方法检查字符串前后的unicode 值,如果存在则删除空格并返回省略的字符串。例如:

public class StringTrimExample{  
public static void main(String args[]){  
String s1="  hello string   ";  
System.out.println(s1+"javatpoint");//without trim()  
System.out.println(s1.trim()+"javatpoint");//with trim()  
}}  

and the results:

结果:

  hello string   javatpoint
hello stringjavatpoint