Efficiently removing specific characters (some punctuation) from Strings in Java?

后端 未结 7 645
青春惊慌失措
青春惊慌失措 2020-12-10 17:14

In Java, what is the most efficient way of removing given characters from a String? Currently, I have this code:

private static String processWord(String x)          


        
相关标签:
7条回答
  • 2020-12-10 17:54

    You could do something like this:

    static String RemovePunct(String input) 
    {
        char[] output = new char[input.length()];
        int i = 0;
    
        for (char ch : input.toCharArray())
        {
            if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) 
            {
                output[i++] = ch;
            }        
        }
    
        return new String(output, 0, i);
    }
    
    // ...
    
    String s = RemovePunct("This is (a) test string.");
    

    This will likely perform better than using regular expressions, if you find them to slow for your needs.

    However, it could get messy fast if you have a long, distinct list of special characters you'd like to remove. In this case regular expressions are easier to handle.

    http://ideone.com/mS8Irl

    0 讨论(0)
提交回复
热议问题