从Java中删除字符串中的空格

zya*_*mat 653 java whitespace

我有一个像这样的字符串:

mysz = "name=john age=13 year=2001";
Run Code Online (Sandbox Code Playgroud)

我想删除字符串中的空格.我试过trim()但这只删除了整个字符串之前和之后的空格.我也尝试了replaceAll("\\W", "")但是=也被删除了.

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

mysz2 = "name=johnage=13year=2001"
Run Code Online (Sandbox Code Playgroud)

Gur*_*oca 1252

st.replaceAll("\\s+","")删除所有空格和不可见字符(例如,制表符\n).


st.replaceAll("\\s+","")st.replaceAll("\\s","")产生相同的结果.

第二个正则表达式比第一个正则表达式快20%,但随着连续空格数量的增加,第一个正则表达式优于第二个正则表达式.


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

st = st.replaceAll("\\s+","")
Run Code Online (Sandbox Code Playgroud)

  • 我想要指出,如果您要使用单个空格(或其他一组字符)替换所有空格,这两个正则表达式将产生不同的结果.如果你有连续的空格,使用\\ s它将用给定的字符替换每个空白字符.给定\\ s +它将用一个替换字符串替换每组空格.我可以看到很多人可能会来这个帖子用一些不仅仅是空字符串的东西替换空格,这可能会有所帮助. (29认同)
  • 只需使用apache-commons中的StringUtils.它是一个名为StringUtils.deleteWhitespace的静态方法. (3认同)
  • 但是,如果它在字符串的开头,则不会删除空格。 (2认同)

nit*_*k01 242

replaceAll("\\s","")
Run Code Online (Sandbox Code Playgroud)

\w =任何单词字符

\W =任何不是单词字符的东西(包括标点符号等)

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

\S =任何不是空格字符的东西(包括字母和数字,以及标点符号等)

(编辑:正如所指出的,如果你想要\s到达正则表达式引擎,你需要转义反斜杠,导致\\s.)


Fle*_*tch 98

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

String mysz2 = mysz.replaceAll("\\s","");
Run Code Online (Sandbox Code Playgroud)

我刚从其他答案中修改了这段代码.我发布它是因为除了正是问题所要求的,它还表明结果作为新字符串返回,原始字符串不会被修改,因为某些答案有点暗示.

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


Erk*_*lat 59

如何replaceAll("\\s", "").请参考这里.

  • 迟到一分钟会有什么不同! (48认同)

小智 40

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到它.commons-lang包括更多,并得到很好的支持.


v.n*_*ahc 34

如果您还需要删除不可破坏的空格,可以像这样升级代码:

st.replaceAll("[\\s|\\u00A0]+", "");
Run Code Online (Sandbox Code Playgroud)


kam*_*zak 29

如果您更喜欢实用程序类到正则表达式,那么Spring Framework中的StringUtils中有一个方法trimAllWhitespace(String).

  • 欢迎提供其他想法.他们会帮助一些人,即使不是每个人. (13认同)

Jon*_*röm 25

你已经从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]);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:
name = john
age = 13
year = 2001


小智 21

你应该用

s.replaceAll("\\s+", "");
Run Code Online (Sandbox Code Playgroud)

代替:

s.replaceAll("\\s", "");
Run Code Online (Sandbox Code Playgroud)

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

  • 我输入了一个快速示例来检查这个,因为它对我来说听起来很奇怪,并且发现不需要添加的加号.消耗了分隔单词的多个空格.这样做的原因很可能是`replaceAll`重复,直到模式与字符串的任何部分都不匹配. (2认同)
  • 确实.`+`可能会使它略微更加CPU友好,因为在单个替换操作中处理连续的空格,但这是唯一的区别.它确实是`All`,而不是`+`正在替换字符串中的非连续空格. (2认同)

Aya*_*ant 8

最简单的方法是使用诸如" " 之org.apache.commons.lang3.StringUtils类的commons-lang3库类commons-lang3-3.1.jar.

StringUtils.deleteWhitespace(String str)在输入字符串上使用静态方法" ",它将从中删除所有空格后返回一个字符串.我尝试了你的示例字符串" name=john age=13 year=2001"并且它完全返回了我想要的字符串 - " name=johnage=13year=2001".希望这可以帮助.


Vin*_*nga 7

你可以这么简单地做到这一点

String newMysz = mysz.replace(" ","");
Run Code Online (Sandbox Code Playgroud)


Sti*_*ahl 7

我正在尝试一个聚合答案,其中测试了删除字符串中所有空格的所有方法。每种方法运行 100 万次,然后取平均值。注意:一些计算将用于总结所有运行。


结果:

@jahir 的回答第一名

  • 带有短文本的 StringUtils:1.21E-4 ms (121.0 ms)
  • 长文本的 StringUtils:0.001648 ms (1648.0 ms)

第二名

  • 带有短文本的字符串生成器:2.48E-4 ms (248.0 ms)
  • 长文本字符串生成器:0.00566 ms (5660.0 ms)

第三名

  • 短文本正则表达式:8.36E-4 ms (836.0 ms)
  • 长文本正则表达式:0.008877 ms (8877.0 ms)

第四名

  • 带有短文本的 For 循环:0.001666 ms (1666.0 ms)
  • For 长文本循环:0.086437 ms (86437.0 ms)

这是代码:

public class RemoveAllWhitespaces {
    public static String Regex(String text){
        return text.replaceAll("\\s+", "");
    }

    public static String ForLoop(String text) {
        for (int i = text.length() - 1; i >= 0; i--) {
            if(Character.isWhitespace(text.codePointAt(i))) {
                text = text.substring(0, i) + text.substring(i + 1);
            }
        }

        return text;
    }

    public static String StringBuilder(String text){
        StringBuilder builder = new StringBuilder(text);
        for (int i = text.length() - 1; i >= 0; i--) {
            if(Character.isWhitespace(text.codePointAt(i))) {
                builder.deleteCharAt(i);
            }
        }

        return builder.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是测试:

import org.junit.jupiter.api.Test;

import java.util.function.Function;
import java.util.stream.IntStream;

import static org.junit.jupiter.api.Assertions.*;

public class RemoveAllWhitespacesTest {
    private static final String longText = "123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222";
    private static final String expected = "1231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc222";

    private static final String shortText = "123 123 \t 1adc \n 222";
    private static final String expectedShortText = "1231231adc222";

    private static final int numberOfIterations = 1000000;

    @Test
    public void Regex_LongText(){
        RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), longText, expected);
    }

    @Test
    public void Regex_ShortText(){
        RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), shortText, expectedShortText);

    }

    @Test
    public void For_LongText(){
        RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), longText, expected);
    }

    @Test
    public void For_ShortText(){
        RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), shortText, expectedShortText);
    }

    @Test
    public void StringBuilder_LongText(){
        RunTest("StringBuilder_LongText", text -> RemoveAllWhitespaces.StringBuilder(text), longText, expected);
    }

    @Test
    public void StringBuilder_ShortText(){
        RunTest("StringBuilder_ShortText", text -> RemoveAllWhitespaces.StringBuilder(text), shortText, expectedShortText);
    }

    private void RunTest(String testName, Function<String,String> func, String input, String expected){
        long startTime = System.currentTimeMillis();
        IntStream.range(0, numberOfIterations)
                .forEach(x -> assertEquals(expected, func.apply(input)));
        double totalMilliseconds = (double)System.currentTimeMillis() - (double)startTime;
        System.out.println(
                String.format(
                        "%s: %s ms (%s ms)",
                        testName,
                        totalMilliseconds / (double)numberOfIterations,
                        totalMilliseconds
                )
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


avn*_*ngr 6

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
Run Code Online (Sandbox Code Playgroud)