我有一个这样的字符串:

mysz = "name=john age=13 year=2001";

我想删除字符串中的空格。我尝试了trim(),但这只删除了整个字符串前后的空格。我还尝试了replaceAll(“\\W”,“”),但随后=也被删除。

如何通过以下方式实现字符串:

mysz2 = "name=johnage=13year=2001"

当前回答

public static void main(String[] args) {        
    String s = "name=john age=13 year=2001";
    String t = s.replaceAll(" ", "");
    System.out.println("s: " + s + ", t: " + t);
}

Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001

其他回答

你已经从Gursel Koca那里得到了正确的答案,但我相信这很有可能不是你真正想要做的事情?

import java.util.Enumeration;
import java.util.Hashtable;

class SplitIt {
  public static void main(String args[])  {

    String person = "name=john age=13 year=2001";

    for (String p : person.split("\\s")) {
      String[] keyValue = p.split("=");
      System.out.println(keyValue[0] + " = " + keyValue[1]);
    }
  }
}

输出:name=约翰年龄=13岁年=2001

有许多方法可以解决这个问题。您可以使用拆分函数或替换字符串的函数。

有关更多信息,请参阅微笑问题http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html

public String removeSpaces(String word){
        StringBuffer buffer = new StringBuffer();
        if(word != null){
            char[] arr = word.toCharArray();
            for(int i=0; i < arr.length; i++){
                if(!Character.isSpaceChar(arr[i])) {
                    buffer.append(arr[i]);
                }                  
            }
        }
        return buffer.toString();
    }

可以使用isWhitespace函数从字符类中删除空白。

public static void main(String[] args) {
    String withSpace = "Remove white space from line";
    StringBuilder removeSpace = new StringBuilder();

    for (int i = 0; i<withSpace.length();i++){
        if(!Character.isWhitespace(withSpace.charAt(i))){
            removeSpace=removeSpace.append(withSpace.charAt(i));
        }
    }
    System.out.println(removeSpace);
}

要删除示例中的空格,这是另一种方法:

String mysz = "name=john age=13 year=2001";
String[] test = mysz.split(" ");
mysz = String.join("", mysz);

它所做的是将其转换为一个以空格为分隔符的数组,然后将数组中的项目组合在一起,而不使用空格。

它工作得很好,很容易理解。