【问题标题】:Removing whitespace from strings in Java从Java中的字符串中删除空格
【发布时间】:2011-07-24 06:29:17
【问题描述】:

我有一个这样的字符串:

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

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

我怎样才能实现一个字符串:

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

【问题讨论】:

标签: java whitespace


【解决方案1】:

您还可以查看下面的 Java 代码。以下代码不使用任何“内置”方法。

/**
 * Remove all characters from an alphanumeric string.
 */
public class RemoveCharFromAlphanumerics {

    public static void main(String[] args) {

        String inp = "01239Debashish123Pattn456aik";

        char[] out = inp.toCharArray();

        int totint=0;

        for (int i = 0; i < out.length; i++) {
            System.out.println(out[i] + " : " + (int) out[i]);
            if ((int) out[i] >= 65 && (int) out[i] <= 122) {
                out[i] = ' ';
            }
            else {
                totint+=1;
            }

        }

        System.out.println(String.valueOf(out));
        System.out.println(String.valueOf("Length: "+ out.length));

        for (int c=0; c<out.length; c++){

            System.out.println(out[c] + " : " + (int) out[c]);

            if ( (int) out[c] == 32) {
                System.out.println("Its Blank");
                 out[c] = '\'';
            }

        }

        System.out.println(String.valueOf(out));

        System.out.println("**********");
        System.out.println("**********");
        char[] whitespace = new char[totint];
        int t=0;
        for (int d=0; d< out.length; d++) {

            int fst =32;



            if ((int) out[d] >= 48 && (int) out[d] <=57 ) {

                System.out.println(out[d]);
                whitespace[t]= out[d];
                t+=1;

            }

        }

        System.out.println("**********");
        System.out.println("**********");

        System.out.println("The String is: " + String.valueOf(whitespace));

    }
}

输入:

String inp = "01239Debashish123Pattn456aik";

输出:

The String is: 01239123456

【讨论】:

    【解决方案2】:
    private String generateAttachName(String fileName, String searchOn, String char1) {
        return fileName.replaceAll(searchOn, char1);
    }
    
    
    String fileName= generateAttachName("Hello My Mom","\\s","");
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        如果要删除字符串中的所有空格:

        public String removeSpace(String str) {
            String result = "";
            for (int i = 0; i < str.length(); i++){
                char c = str.charAt(i);        
                if(c!=' ') {
                    result += c;
                }
            }
            return result;
        }
        

        【讨论】:

        • 这个效率很低,请关注StringBuilder
        【解决方案5】:

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


        结果:

        @jahir 's answer第一名

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

        第二名

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

        第三名

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

        第四名

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

        代码如下:

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

        【讨论】:

          【解决方案6】:
          package com.sanjayacchana.challangingprograms;
          
          public class RemoveAllWhiteSpacesInString {
          
              public static void main(String[] args) {
                  
                  String str = "name=john age=13 year=2001";
                  
                  str = str.replaceAll("\\s", ""); 
                  
                  System.out.println(str);
                  
                  
              }
          
          }
          

          【讨论】:

          • 这个答案与其他已经存在的答案有何不同?
          • 它对我很有用
          猜你喜欢
          • 2019-09-10
          • 2017-11-20
          • 2011-09-21
          • 2020-10-20
          相关资源
          最近更新 更多