如何通过caesar密码中的lowcase和大写将字母循环分别保持?
我正在尝试挑战凯撒密码问题,但我陷入了一个条件,这个问题不仅要移动n个元素位置,而且还在内部将循环保持在ASCII范围内,因此“ Z”将转到“ C”不'|'|'如果n = 3。 有人能否启发我如何在角色内部循环。ISLETTER和CHARIEN.ISSISLOWERCASE基础我现在正在做的事情?希望我在轨道上,这是我的代码。谢谢
public static String caesarCipher(String s, int k) {
if(k>26){
k = k % 26;
}else if (k<26){
k = (k % 26) + 26;
}
String result = new String();
int length = s.length();
for(int i=0; i<length; i++){
char ch = s.charAt(i);
if(Character.isLetter(ch)){ // only for alphabet
if(Character.isLowerCase(ch)){ // for lower case a-z
char cha = (char)(ch+k);
if(cha > 'z'){
result += (char)(ch - (26 - k));
} else {
result += cha;
}
} else if(Character.isUpperCase(ch)){ // for upper case a-z
char cha = (char)(ch+k);
if(cha > 'Z'){
result += (char)(ch - (26 - k));
}else {
result += cha;
}
}
} else {
result += ch;
}
}
return result;
}
I am trying to challenge the Caesar Cipher problem, but am stuck at one condition, the question not only move n element position but also keep loop internally in the ASCII range, so 'z' will go to 'c' not '|' if n=3.
Could someone enlighten me how to get loop inside of Character.isLetter and Character.isLowerCase base on what I am doing now? hope I am on the track, and here is my code. Thank you
public static String caesarCipher(String s, int k) {
if(k>26){
k = k % 26;
}else if (k<26){
k = (k % 26) + 26;
}
String result = new String();
int length = s.length();
for(int i=0; i<length; i++){
char ch = s.charAt(i);
if(Character.isLetter(ch)){ // only for alphabet
if(Character.isLowerCase(ch)){ // for lower case a-z
char cha = (char)(ch+k);
if(cha > 'z'){
result += (char)(ch - (26 - k));
} else {
result += cha;
}
} else if(Character.isUpperCase(ch)){ // for upper case a-z
char cha = (char)(ch+k);
if(cha > 'Z'){
result += (char)(ch - (26 - k));
}else {
result += cha;
}
}
} else {
result += ch;
}
}
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论