如何通过caesar密码中的lowcase和大写将字母循环分别保持?

发布于 2025-02-05 07:19:44 字数 1192 浏览 1 评论 0原文

我正在尝试挑战凯撒密码问题,但我陷入了一个条件,这个问题不仅要移动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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文