我有一个这样的字符串:

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

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

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

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

当前回答

使用mysz.replaceAll(“\\s+”,“”);

其他回答

您需要的代码是

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

这将删除所有空白。

replaceAll("\\s","")

\w=任何单词字符

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

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

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

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

你可以这么简单地通过

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

在Kotlin中使用st.replaceAll(“\\s+”,“”)时,请确保使用Regex包装“\\s+”:

"myString".replace(Regex("\\s+"), "")

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

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