我有一个这样的字符串:

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

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

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

mysz2 = "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();

    }

}

其他回答

public static String removeWhiteSpaces(String str){
    String s = "";
    char[] arr = str.toCharArray();
    for (int i = 0; i < arr.length; i++) {
        int temp = arr[i];
        if(temp != 32 && temp != 9) { // 32 ASCII for space and 9 is for Tab
            s += arr[i];
        }
    }
    return s;
}

这可能会有所帮助。

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

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

private String generateAttachName(String fileName, String searchOn, String char1) {
    return fileName.replaceAll(searchOn, char1);
}


String fileName= generateAttachName("Hello My Mom","\\s","");
public String removeSpaces(String word){
        StringBuffer buffer = new StringBuffer();
        if(word != null){
            char[] arr = word.toCharArray();
            for(int i=0; i < arr.length; i++){
                if(!Character.isSpaceChar(arr[i])) {
                    buffer.append(arr[i]);
                }                  
            }
        }
        return buffer.toString();
    }

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


结果:

@jahir回答的第一名

带短文本的StringUtils:1.21E-4毫秒(121.0毫秒)带长文本的StringUtils:0.001648毫秒(1648.0毫秒)

第二名

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

第三名

带短文本的Regex:8.36E-4 ms(836.0 ms)带长文本的Regex:0.008877毫秒(8877.0毫秒)

第四名

对于短文本循环:0.001666 ms(1666.0 ms)对于长文本循环: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();
    }
}

以下是测试:

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