gpt4 book ai didi

java - 凯撒移位密码java

转载 作者:行者123 更新时间:2023-12-01 11:57:11 24 4
gpt4 key购买 nike

我正在尝试为 Java 实现一个基本的凯撒移位密码,将所有字母移位 13。这是迄今为止我的代码。

    public static String cipher(String sentence){
String s = "";
for(int i = 0; i < sentence.length(); i++){
char c = (char)(sentence.charAt(i) + 13);
if (c > 'z')
s += (char)(sentence.charAt(i) - 13);
else
s += (char)(sentence.charAt(i) + 13);
}
return s;
}

但是,该程序还更改了数字和特殊字符的值,但我不希望这样。

String sentence = "abc123";

返回“nop>?@”

有没有一种简单的方法来避免特殊字符并只关注字母?

编辑:我应该提到我想保留所有其他位。因此“abc123”将返回“nop123”。

最佳答案

在下面的示例中,我仅加密字母(更准确地说是 A-Z 和 a-z),并添加了使用任何偏移量的可能性:

public static String cipher(String sentence, int offset) {
String s = "";
for(int i = 0; i < sentence.length(); i++) {
char c = (char)(sentence.charAt(i));
if (c >= 'A' && c <= 'Z') {
s += (char)((c - 'A' + offset) % 26 + 'A');
} else if (c >= 'a' && c <= 'z') {
s += (char)((c - 'a' + offset) % 26 + 'a');
} else {
s += c;
}
}
return s;
}

这里有一些例子:

cipher("abcABCxyzXYZ123", 1)   // output: "bcdBCDyzaYZA123"
cipher("abcABCxyzXYZ123", 2) // output: "cdeCDEzabZAB123"
cipher("abcABCxyzXYZ123", 13) // output: "nopNOPklmKLM123"

注意:根据您的代码,我假设您只想处理/加密“普通”26 个字母。这意味着像这样的字母德语“ü”(Character.isLetter('ü') 将返回 true)保持未加密状态。

关于java - 凯撒移位密码java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28363966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com