我有一个这样的字符串:

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

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

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

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

当前回答

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

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

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

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

其他回答

如果您也需要删除不可破坏的空格,可以这样升级代码:

st.replaceAll("[\\s|\\u00A0]+", "");

st.replaceAll(“\\s+”,“”)删除所有空格和不可见字符(例如,tab,\n)。


st.replaceAll(“\\s+”,“”)和st.replaceAll(“\\s”,“)产生相同的结果。

第二个正则表达式比第一个正则表达式快20%,但随着连续空格数的增加,第一个正则正则表达式的性能比第二个更好。


如果不直接使用,则将值分配给变量:

st = st.replaceAll("\\s+","")

可以使用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);
}
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;
}

这可能会有所帮助。

import java.util.*;
public class RemoveSpace {
    public static void main(String[] args) {
        String mysz = "name=john age=13 year=2001";
        Scanner scan = new Scanner(mysz);

        String result = "";
        while(scan.hasNext()) {
            result += scan.next();
        }
        System.out.println(result);
    }
}