Caesar cipher
Easy TimeO(n) SpaceO(n)
Given a string s and a number shift, return the string with every letter moved that many places forward through the alphabet, wrapping from z back round to a. Each letter keeps its case, so an uppercase letter stays uppercase and a lowercase one stays lowercase. Digits, punctuation and spaces are left untouched and appear in the answer exactly as they went in.
Examples
Example 1
- Input
- s = "Hello, World!"shift = 3
- Output
- Every letter moves three places; the comma, the space and the exclamation mark are copied as they stand.
"Khoor, Zruog!"
Example 2
- Input
- s = "xyz"shift = 3
- Output
- All three run past the end of the alphabet and come back round to its start.
"abc"
The Code
function caesar(s, shift) {
const A = 65;
const a = 97;
let out = "";
for (let i = 0; i < s.length; i++) {
const code = s.charCodeAt(i);
if (code >= a && code <= a + 25) {
out += String.fromCharCode(((code - a + shift) % 26) + a);
} else if (code >= A && code <= A + 25) {
out += String.fromCharCode(((code - A + shift) % 26) + A);
} else {
out += s[i];
}
}
return out;
}
caesar("Hello, World!", 3);Done
The first 11 calls, of 15. This one does not fit on a page.
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Valid anagram Count letters up with one word, down with the other.
- Common prefix Start with the whole first word, shrink until everything matches.
- Run-length encoding Collapse each run of repeats into a character and a count.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.