我有一个这样的字符串:

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

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

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

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

当前回答

将每组文本分隔成自己的子字符串,然后连接这些子字符串:

public Address(String street, String city, String state, String zip ) {
    this.street = street;
    this.city = city;
    // Now checking to make sure that state has no spaces...
    int position = state.indexOf(" ");
    if(position >=0) {
        //now putting state back together if it has spaces...
        state = state.substring(0, position) + state.substring(position + 1);  
    }
}

其他回答

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

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

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

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

如果要删除字符串中的所有空格:

public String removeSpace(String str) {
    String result = "";
    for (int i = 0; i < str.length(); i++){
        char c = str.charAt(i);        
        if(c!=' ') {
            result += c;
        }
    }
    return result;
}

\W表示“非文字字符”。空白字符的模式为%s。这在Pattern javadoc中有很好的记录。

replaceAll("\\s","")

\w=任何单词字符

\W=任何非单词字符(包括标点符号等)

\s=任何空格字符(包括空格、制表符等)

\S=非空格字符的任何内容(包括字母和数字以及标点符号等)

(编辑:如前所述,如果您希望到达正则表达式引擎,则需要转义反斜杠,从而导致\\s。)

public static String removeWhiteSpaces(String str){
    String s = "";
    char[] arr = str.toCharArray();
    for (int i = 0; i < arr.length; i++) {
        int temp = arr[i];
        if(temp != 32 && temp != 9) { // 32 ASCII for space and 9 is for Tab
            s += arr[i];
        }
    }
    return s;
}

这可能会有所帮助。