我有一个这样的字符串:

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

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

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

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

当前回答

试试看:

String str="name=john age=13 year=2001";
String s[]=str.split(" ");
StringBuilder v=new StringBuilder();
for (String string : s) {
    v.append(string);
}
str=v.toString();

其他回答

您需要的代码是

str.replaceAll("\\s","");

这将删除所有空白。

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

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

你可以这么简单地通过

String newMysz = mysz.replace(" ","");

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

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);  
    }
}

如果您更喜欢实用程序类而不是正则表达式,那么Spring Framework中的StringUtils中有一个方法trimAllWhitespace(String)。