Caesar Cipher

Sort by

recency

|

231 Discussions

|

  • + 0 comments

    in JS:

    function caesarCipher(s, k) {
        const alphabets = 'abcdefghijklmnopqrstuvwxyz'
        const alLength = alphabets.length;
        let changedString = '';
        
        for (let char of s) {
            const isUpperCase = char === char.toUpperCase();
            char = char.toLowerCase();
            if (alphabets.includes(char)){
                let newIdx = (alphabets.indexOf(char) + k) % alLength;
                if (newIdx < 0) newIdx += alLength;
                let changedLetter = alphabets[newIdx];
                if (isUpperCase) {
                    changedLetter = changedLetter.toLocaleUpperCase();
                }
                changedString += changedLetter;
                
            } else {
                changedString += char;
            }
        }
        return changedString;
    
  • + 0 comments

    def caesarCipher(s, k): alp ="abcdefghijklmnopqrstuvwxyz" if k>2: if k>26: k= k%26 ro = alp[k:]+alp[:k] j= list(s) lt = []

    for i in j:
        if i.lower() not in alp:
            lt.append(i)
        elif i.isupper():
            k= alp.index(i.lower())
            lt.append((ro[k]).upper())
        else:
            k= alp.index(i)
            lt.append(ro[k])
    fin = ''.join(lt)
    return fin
    
  • + 0 comments

    Here is my Python3 approach

    def caesarCipher(s, k):
        # Write your code here
        strBuild = ""
        for i in s:
            if (str.isalpha(i)):
                asc = ord(i) + k
                if (i.isupper() and asc > 90):
                    while asc > 90:
                        asc = asc - 26
                    strBuild += chr(asc)
                elif (i.islower() and asc > 122):
                    while asc > 122:
                        asc = asc - 26
                    strBuild += chr(asc)
                else:
                    strBuild += chr(asc)
            else:
                strBuild += i
            
        print(strBuild)
        return strBuild
    
  • + 0 comments
    import string
    
    def caesarCipher(s, k):
        abc = string.ascii_lowercase * 5 + string.ascii_uppercase * 5
        return ''.join([abc[abc.find(x) + k] if x in abc else x for x in s])
    
  • + 0 comments
    def caesarCipher(s, k):
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        result = ''
        
        for char in s:
            if char.lower() in alphabet:
                idx = alphabet.index(char.lower()) + k
                c = alphabet[idx % len(alphabet)]
                
                if char.isupper():
                    result += c.upper()
                else:
                    result += c
                    
            else:
                result += char
                
        return result