Caesar Cipher

  • + 0 comments

    Java 15 using streams API:

        public static String caesarCipher(String s, int k) {
            return s.chars()
                .map(c -> {
                    var isUpperLetter = 'A' <= c && c <= 'Z';
                    var isLowerLetter = 'a' <= c && c <= 'z';
                    if (isUpperLetter || isLowerLetter) {
                        var wrapStart = isUpperLetter ? 'A' : 'a';
                        var wrapEnd = isUpperLetter ? 'Z' : 'z';
                        var alphabetIdx = c - wrapStart;
                        var alphabetSize = wrapEnd - wrapStart + 1;
                        var newAlphabetIdx = (alphabetIdx + k) % alphabetSize;
                        return wrapStart + newAlphabetIdx;
                    } else {
                        // c is not alphabetical. Skip it.
                        return c;
                    }
                })
                .collect(
                    StringBuilder::new, 
                    StringBuilder::appendCodePoint, 
                    StringBuilder::append
                )
                .toString();
        }