public static String LetterChanges(String str) {
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String res="";
for (int i = 0; i < str.length (); i ) {
for (int j = 0; j < alphabet.length (); j ) {
if (str.charAt (i) == alphabet.charAt (j)) {
res = str.replace (str.charAt (i), alphabet.charAt (j 1));
break;
}
}
}
return res;
}
Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)
For example I passing "Hello" as parameter str, and want to get "Ifmmp", but I got "Hellp" changing only last letter
CodePudding user response:
Instead using
res = str.replace (str.charAt (i), alphabet.charAt (j 1));
try it
res = alphabet.charAt(j 1);
CodePudding user response:
You don't need a nested loop. The letters of the alphabet have sequential code points, so all you need to do is get the difference between the character you want to increase an a
(or A
for capitals), add one to it, modulo 26 for wrapping around z
(or Z
), and add this new distance back to a
. I.e.:
public static String letterChanges(String str) {
StringBuilder res = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i) {
char ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
ch = (char) ((ch 1 - 'A') % 26 'A');
} else if (Character.isLowerCase(ch)) {
ch = (char) ((ch 1 - 'a') % 26 'a');
}
res.append(ch);
}
return res.toString();
}