Caesar Cipher

  • + 0 comments

    C++

    string caesarCipher(string s, int k) {
        string alphabet = "abcdefghijklmnopqrstuvwxyz";
        int shift = k % alphabet.size(); // k % 26
        string rotated_alphabet = alphabet.substr(shift) 
                                + alphabet.substr(0, shift);
        
        string result;
        for (const char& c : s) {
            if (!std::isalpha(c)) {
                result += c;
            } else {
                char ec = rotated_alphabet[std::tolower(c) - 'a'];
    
                if (std::isupper(c)) {
                    ec = std::toupper(ec);
                }
                
                result += ec;            
            }
        }
        
        return result;
    }