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

前端 未结 9 1080
梦谈多话
梦谈多话 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:45

    I just implemented this utility class that replaces a char or a group of chars of a String. It is equivalent to bash tr and perl tr///, aka, transliterate. I hope it helps someone!

    package your.package.name;
    
    /**
     * Utility class that replaces chars of a String, aka, transliterate.
     * 
     * It's equivalent to bash 'tr' and perl 'tr///'.
     *
     */
    public class ReplaceChars {
    
        public static String replace(String string, String from, String to) {
            return new String(replace(string.toCharArray(), from.toCharArray(), to.toCharArray()));
        }
    
        public static char[] replace(char[] chars, char[] from, char[] to) {
    
            char[] output = chars.clone();
            for (int i = 0; i < output.length; i++) {
                for (int j = 0; j < from.length; j++) {
                    if (output[i] == from[j]) {
                        output[i] = to[j];
                        break;
                    }
                }
            }
            return output;
        }
    
        /**
         * For tests!
         */
        public static void main(String[] args) {
    
            // Example from: https://en.wikipedia.org/wiki/Caesar_cipher
            String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
            String from = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            String to = "XYZABCDEFGHIJKLMNOPQRSTUVW";
    
            System.out.println();
            System.out.println("Cesar cypher: " + string);
            System.out.println("Result:       " + ReplaceChars.replace(string, from, to));
        }
    }
    

    This is the output:

    Cesar cypher: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
    Result:       QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
    

提交回复
热议问题