我有一个这样的字符串:

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

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

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

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

当前回答

这个问题最正确的答案是:

String mysz2 = mysz.replaceAll("\\s","");

我只是根据其他答案改编了这段代码。我之所以发布它,是因为除了完全符合问题的要求之外,它还表明结果是作为一个新字符串返回的,原始字符串并没有像某些答案那样被修改。

(有经验的Java开发人员可能会说“当然,您实际上不能修改字符串”,但这个问题的目标受众可能不知道这一点。)

其他回答

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

我希望这对你有帮助。

使用apache字符串util类更好地避免NullPointerException

org.apache.commons.lang3.StringUtils.replace("abc def ", " ", "")

输出

abcdef
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

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

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

    }

}

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

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