我有一个这样的字符串:

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

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

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

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

当前回答

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

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

其他回答

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

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

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

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

在java中,我们可以执行以下操作:

String pattern="[\\s]";
String replace="";
part="name=john age=13 year=2001";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(part);
part=m.replaceAll(replace);
System.out.println(part);

为此,您需要将以下程序包导入到程序中:

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

我希望这对你有帮助。

你应该使用

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

而不是:

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

这样,它将在每个字符串之间使用多个空格。上述正则表达式中的+符号表示“一个或多个\ s”

--\s=任何空格字符(包括空格、制表符等)。为什么这里需要s+?

public static void main(String[] args) {        
    String s = "name=john age=13 year=2001";
    String t = s.replaceAll(" ", "");
    System.out.println("s: " + s + ", t: " + t);
}

Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001

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