我有一个这样的字符串:

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

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

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

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

当前回答

处理字符串操作的一种方法是来自Apache commons的StringUtils。

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

你可以在这里找到它。commons-lang包含更多内容,并且得到了很好的支持。

其他回答

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

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);  
    }
}
replaceAll("\\s","")

\w=任何单词字符

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

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

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

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

您需要的代码是

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

这将删除所有空白。

import java.util.*;
public class RemoveSpace {
    public static void main(String[] args) {
        String mysz = "name=john age=13 year=2001";
        Scanner scan = new Scanner(mysz);

        String result = "";
        while(scan.hasNext()) {
            result += scan.next();
        }
        System.out.println(result);
    }
}

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

对输入字符串使用静态方法“StringUtils.deleteWhitespace(Stringstr)”&它将在删除所有空格后返回一个字符串。我尝试了示例字符串“name=johnage=13year=2001”&它返回了您想要的字符串-“name=johnage=13yeal=2001”。希望这有帮助。