我有一个这样的字符串:

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

其他回答

提供了相当多的答案。我想给出一个比正则表达式更易读、更好的解决方案。

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

public class RemoveAllWhitespaceTest {

    public static void main(String[] args) throws IOException {

        String str1 = "\n\tThis is my string \n \r\n  !";

        System.out.println("[" + str1 + "]");

        System.out.println("Whitespace Removed:");

        System.out.println("[" + StringUtils.deleteWhitespace(str1) + "]");

        System.out.println();

    }

}

在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;

我希望这对你有帮助。

你可以这么简单地通过

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

最简单的方法是使用commons-lang3库的org.apachemons.lang3.StringUtils类,例如“commons-lang3-3.1.jar”。

对输入字符串使用静态方法“StringUtils.deleteWhitespace(Stringstr)”&它将在删除所有空格后返回一个字符串。我尝试了示例字符串“name=johnage=13year=2001”&它返回了您想要的字符串-“name=johnage=13yeal=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);  
    }
}