我有一个这样的字符串:

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

其他回答

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

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

字符串中也存在其他空格字符。。所以我们可能需要从字符串中替换空格字符。

例如:无杆空间、三杆EM空间、打孔空间

以下是空格字符列表http://jkorpela.fi/chars/spaces.html

所以我们需要修改

\u2004我们的三人空间

s.replaceAll(“[\u0020\u2004]”,“”)

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


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

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


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

st = st.replaceAll("\\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;
}

这可能会有所帮助。

你已经从Gursel Koca那里得到了正确的答案,但我相信这很有可能不是你真正想要做的事情?

import java.util.Enumeration;
import java.util.Hashtable;

class SplitIt {
  public static void main(String args[])  {

    String person = "name=john age=13 year=2001";

    for (String p : person.split("\\s")) {
      String[] keyValue = p.split("=");
      System.out.println(keyValue[0] + " = " + keyValue[1]);
    }
  }
}

输出:name=约翰年龄=13岁年=2001