What is an efficient way to replace many characters in a string?

前端 未结 9 1079
梦谈多话
梦谈多话 2020-12-28 14:31

String handling in Java is something I\'m trying to learn to do well. Currently I want to take in a string and replace any characters I find.

Here is my current inef

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 14:47

    You could create a table of String[] which is Character.MAX_VALUE in length. (Including the mapping to lower case)

    As the replacements got more complex, the time to perform them would remain the same.

    private static final String[] REPLACEMENT = new String[Character.MAX_VALUE+1];
    static {
        for(int i=Character.MIN_VALUE;i<=Character.MAX_VALUE;i++)
            REPLACEMENT[i] = Character.toString(Character.toLowerCase((char) i));
        // substitute
        REPLACEMENT['á'] =  "a";
        // remove
        REPLACEMENT['-'] =  "";
        // expand
        REPLACEMENT['æ'] = "ae";
    }
    
    public String convertWord(String word) {
        StringBuilder sb = new StringBuilder(word.length());
        for(int i=0;i

提交回复
热议问题