Caesar Cipher

  • + 0 comments

    did it using ascii value in Java public static String caesarCipher(String s, int k) { String s1 = ""; int k1;

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
            k1 = k;
    
            while (k1 > 0) {
                if (Character.isLowerCase(c) && c + k1 <= 'z') {
                    c = (char) (c + k1);
                    break;
                } else if (Character.isLowerCase(c) && c + k1 > 'z') {
                    k1 -= ('z' - c + 1);  
                    c = 'a';  
                } else if (Character.isUpperCase(c) && c + k1 <= 'Z') {
                    c = (char) (c + k1);
                    break;
                } else if (Character.isUpperCase(c) && c + k1 > 'Z') {
                    k1 -= ('Z' - c + 1); 
                    c = 'A'; 
                }
            }
    
            s1 += c;
        } else {
            s1 += c; 
        }
    }
    
    return s1;
    

    }