Caesar Cipher

  • + 0 comments

    Java with explain.

    String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //26+26 symbols
            String result = "";
            k = k % 26;//correct rotate amount
            for (int i = 0; i < s.length(); i++) {
                Character currentChar = s.charAt(i);
                int index = alphabet.indexOf(currentChar); //get index of char
                if (index < 26 && index + k > 25 //correct index if it goes abroad
                        || index < 52 && index + k > 51) { //for uppercase
                    index -= 26;
                }
                if (Character.isLetter(currentChar)) { //if it not a char (-' e.t.c)
                    result = result + alphabet.charAt(index + k);
                } else {
                    result = result + s.charAt(i);
                }
            }
            return result;