目前,我正在编写一个程序,它使用Java在给定的字符串上执行ROT-1直到并包含ROT-25。在我的研究开始时,我发现了this代码:
public class Rot13 {
public static void main(String[] args) {
String s = args[0];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'A' && c <= 'M') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
else if (c >= 'N' && c <= 'Z') c -= 13;
StdOut.print(c);
}
StdOut.println();
}
}
经过一些麻烦,我得到了这个:
private static void rotALL(String input) {
//Loop 25 times, starting with ROT-1 and ending at ROT-25 (every possibliity besides the original input)
for (int i = 1; i < 26; i++) {
int rot = 26 - i;
System.out.print("ROT" + rot + ": ");
for (int charIndex = 0; charIndex < input.length(); charIndex++) {
char c = input.charAt(charIndex);
int inta = 97; //a in the ASCII table
int intaWithRot = inta + rot;
int intA = 65; //A in the ASCII table
int intAWithRot = intA + rot;
int intaWithRotPlusOne = intaWithRot + 1;
int intaWithRotPlusi = intaWithRot + i;
int intAWithRotPlusOne = intAWithRot + 1;
int intAWithRotPlusi = intAWithRot + i;
if (c >= inta && c <= intaWithRot) {
c += rot;
} else if (c >= intA && c <= intAWithRot) {
c += rot;
} else if (c >= intaWithRotPlusOne && c <= intaWithRotPlusi) {
c -= rot;
} else if (c >= intAWithRotPlusOne && c <= intAWithRotPlusi) {
c -= rot;
}
System.out.print(c);
}
System.out.println();
}
现在我遇到了问题:
当我输入“grfg qngn”,这是使用ROT-13的“测试数据”时,我对ROT-13的输出是“ROT13:test d {t {”,“{”和“a” “在ASCII表中彼此相距26个位置,但我不知道为什么会出现这种错误,当”e“等字母正确显示时。
如何更改此算法,使其循环通过ROT-1到ROT-25?我认为这应该可以解决问题,但我遗漏了一些东西。
提前致谢并亲切的问候!
答案 0 :(得分:2)
有数百种方法可以解决这个问题,作为学习者,你应该全部探索它们。关于使用模“%”运算符的评论可以通过这个小方法来说明:
private static char rotateLower(char c, int rot) {
int baseBand = c - 'a';
int modified = (baseBand + rot) % 26;
return (char) (modified + 'a');
}
答案 1 :(得分:0)
/**
* Returns a list with Strings which are rotated ROT-n. n = 26 - listIndex
*
* Source: http://www.rot-n.com/?page_id=4
*
* @param input the string to mutate
* @param numeric include numeric values
* @return a list with mutated strings
*/
private static List<String> rotN(String input, boolean numeric) {
List<String> output = new ArrayList<>();
for (int n = 0; n < 26; n++) {
String result = "";
int length = input.length();
for (int i = 0; i < length; i++) {
char ascii = input.charAt(i);
char rotated = ascii;
//Capital letters are 60 to 90
if (ascii > 64 && ascii < 91) {
rotated = (char) (rotated + n);
if (rotated > 90) {
rotated += -90 + 64;
}
if (rotated < 65) {
rotated += -64 + 90;
}
} else if (ascii > 96 && ascii < 123) { //Lowercase letters are between 97 and 122
rotated = (char) (rotated + n);
if (rotated > 122) {
rotated += -122 + 96;
}
if (rotated < 97) {
rotated += -96 + 122;
}
}
//Numeric values are between 48 to 57
if (numeric && ascii > 47 && ascii < 58) {
rotated = (char) (rotated + n);
if (rotated > 47) {
rotated += -57 + 47;
}
if (rotated < 58) {
rotated += -47 + 57;
}
}
result += (char) rotated;
}
output.add(result);
}
return output;
}
这是我找到的解决方案,它正在发挥作用。