我有一个这样的字符串:

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

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

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

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

当前回答

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


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

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


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

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

其他回答

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

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

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

使用Pattern And Matcher,它更具动态性。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemovingSpace {

    /**
     * @param args
     * Removing Space Using Matcher
     */
    public static void main(String[] args) {
        String str= "jld fdkjg jfdg ";
        String pattern="[\\s]";
        String replace="";

        Pattern p= Pattern.compile(pattern);
        Matcher m=p.matcher(str);

        str=m.replaceAll(replace);
        System.out.println(str);    
    }
}

试试看:

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

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

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