Removing whitespace from strings in Java

前端 未结 30 1872
一个人的身影
一个人的身影 2020-11-22 05:01

I have a string like this:

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

I want to remove the whitespaces in the string. I tried trim()

相关标签:
30条回答
  • 2020-11-22 05:45
    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:45

    To remove spaces in your example, this is another way to do it:

    String mysz = "name=john age=13 year=2001";
    String[] test = mysz.split(" ");
    mysz = String.join("", mysz);
    

    What this does is it converts it into an array with the spaces being the separators, and then it combines the items in the array together without the spaces.

    It works pretty well and is easy to understand.

    0 讨论(0)
  • 2020-11-22 05:45

    I am trying an aggregation answer where I test all ways of removing all whitespaces in a string. Each method is ran 1 million times and then then the average is taken. Note: Some compute will be used on summing up all the runs.


    Results:

    1st place from @jahir 's answer

    • StringUtils with short text: 1.21E-4 ms (121.0 ms)
    • StringUtils with long text: 0.001648 ms (1648.0 ms)

    2nd place

    • String builder with short text: 2.48E-4 ms (248.0 ms)
    • String builder with long text: 0.00566 ms (5660.0 ms)

    3rd place

    • Regex with short text: 8.36E-4 ms (836.0 ms)
    • Regex with long text: 0.008877 ms (8877.0 ms)

    4th place

    • For loop with short text: 0.001666 ms (1666.0 ms)
    • For loop with long text: 0.086437 ms (86437.0 ms)

    Here is the code:

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

    Here are the tests:

    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
                    )
            );
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:46

    One way to handle String manipulations is StringUtils from Apache commons.

    String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);
    

    You can find it here. commons-lang includes lots more and is well supported.

    0 讨论(0)
  • 2020-11-22 05:47

    The most correct answer to the question is:

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

    I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.

    (Experienced Java developers might say "of course, you can't actually modify a String", but the target audience for this question may well not know this.)

    0 讨论(0)
  • 2020-11-22 05:49

    You can do it so simply by

    String newMysz = mysz.replace(" ","");
    
    0 讨论(0)
提交回复
热议问题