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

前端 未结 9 1104
梦谈多话
梦谈多话 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条回答
  •  误落风尘
    2020-12-28 14:52

    My implementation is based on look up table.

    public static String convertWord(String str) {
        char[] words = str.toCharArray();
        char[] find = {'á','é','ú','ý','ð','ó','ö','æ','þ','-','.',
                '/'};
        String[] replace = {"a","e","u","y","d","o","o","ae","th"};
        StringBuilder out = new StringBuilder(str.length());
        for (int i = 0; i < words.length; i++) {
            boolean matchFailed = true;
            for(int w = 0; w < find.length; w++) {
                if(words[i] == find[w]) {
                    if(w < replace.length) {
                        out.append(replace[w]);
                    }
                    matchFailed = false;
                    break;
                }
            }
            if(matchFailed) out.append(words[i]);
        }
        return out.toString();
    }
    

提交回复
热议问题