You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#凯撒密码解密时触发数组越界异常,求解决方案

凯撒密码解密时数组越界问题分析与修复

问题原因

  1. 加密阶段符号处理遗漏:加密时遇到符号(如!)执行continue跳过赋值,导致结果数组对应位置保留默认空字符\0。解密时这个空字符不在字母数组中,Array.IndexOf返回-1,加上负偏移量后得到负数索引,访问字母数组时触发越界异常。
  2. 负索引未处理:C#中负数取模结果仍为负数,比如(-1 -3) %26 = -4,直接用这个负数访问数组必然报错。

解决办法

  • 保留符号到结果数组:遇到符号时,直接将符号赋值到结果数组对应位置,而非跳过。
  • 修正索引计算逻辑:确保计算后的索引始终在0-25范围内,负数索引通过加上26转为正数后再取模。

修改后的完整代码

static void Main(string[] args) 
{
    Console.Write("ENTER MESSAGE: ");
    string messageIn = Console.ReadLine().ToLower();

    Console.Write("MODIFIER?: ");
    int mod = Int32.Parse(Console.ReadLine());

    char[] secretMessage = messageIn.ToCharArray();

    char[] encrypt = Crypt(secretMessage, mod);
    string encryption = String.Join("", encrypt);
    Console.WriteLine($"Encryption: {encryption}");

    char[] decrypt = Crypt(encrypt, -mod);
    string decryption = String.Join("", decrypt);
    Console.WriteLine($"Decryption: {decryption}");
}

static char[] Crypt(char[] input, int modi) 
{ 
    char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    char[] symbs = {'!', '@', '#', '$', '%', ' '};

    char[] cryptMesssageArray = new char[input.Length];

    for (int i = 0; i < input.Length; i++) 
    {
        bool isSymbol = false;
        foreach (char symb in symbs) 
        {
            if (input[i] == symb) 
            {
                isSymbol = true;
                break; // 找到匹配符号后直接跳出循环,提升效率
            }
        }
    
        if (isSymbol) 
        {
            cryptMesssageArray[i] = input[i]; // 保留符号
            continue;
        }

        char secretChar = input[i];
        int originalIndex = Array.IndexOf(alphabet, secretChar);
        int newIndex = (originalIndex + modi) % 26;
        // 处理负数索引
        if (newIndex < 0)
        {
            newIndex += 26;
        }
        char cryptChar = alphabet[newIndex];

        cryptMesssageArray[i] = cryptChar;
    }

    return cryptMesssageArray;
}

验证结果

输入消息hello!、偏移量3时:

  • 加密结果:khoor!(保留符号)
  • 解密结果:hello!,无异常抛出

内容的提问来源于stack exchange,提问作者CassiTheNerd420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:22:53