Prompt
Given a non-empty string of lowercase letters and a non-negative integer representing a
key, write a function that returns a new string obtained by shifting every letter in the input
string by k positions in the alphabet, where k is the key.
Note that letters should “wrap” around the alphabet; in other words, the letter z shifted by one returns the letter a .
Sample Input
string = 'xyz'
key = 2
Sample Output
"zab"
Solution 1
import java.util.*;
class Program {
public static String caesarCypherEncryptor(String str, int key) {
char[] newLetters = new char[str.length()];
int newKey = key % 26;
for(int i = 0; i < str.length(); i++) {
newLetters[i] = getNewLetters(str.charAt(i), newKey);//A
}
return new String(newLetters);//B
}
public static char getNewLetters(char letter, int key) {
int newLetterCode = letter + key;//C
return newLetterCode <= 122 ? (char) newLetterCode : (char) (96 + newLetterCode % 122);
}
}
# 1A
# 1B
# 1C
Solution 2
import java.util.*;
class Program {
public static String caesarCypherEncryptor(String str, int key) {
char[] newLetters = new char[str.length()];
int newKey = key % 26;
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < str.length(); i++){
newLetters[i] = getNewLetters(str.charAt(i), newKey, alphabet);
}
return new String(newLetters);
}
public static char getNewLetters(char letter, int key, String alphabet) {
int newLetterCode = alphabet.indexOf(letter) + key; //A
return newLetterCode <= 25 ? alphabet.charAt(newLetterCode) : alphabet.charAt(newLetterCode - 26);
}
}