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

凯撒密码开发遇阻:foreach/for循环字符递增实现故障求助

凯撒密码程序问题修复指南

嘿,我来帮你搞定这个凯撒密码的问题!先拆解你代码里的核心错误,再给你一个能正常运行的基础实现方案。

你的代码里的关键问题

1. For循环的致命错误

你在for循环里写了i +=3,完全搞错了操作对象:

  • 这里的i是数组的索引变量,修改它会直接跳过大量元素,甚至超出数组的索引范围(比如数组长度是5,i从0变成3,下一次循环i++到4,再加3变成7,letters[7]就会触发索引越界异常——这就是程序崩溃的原因)。
  • 你根本没对字符本身做偏移操作,只是跳着输出了原数组里的字符,完全没实现加密逻辑。

2. Foreach循环的问题

在C#的foreach循环里,迭代变量(比如你写的char i)是只读的,你不能直接对它执行i +=3——编译器其实应该会给你报错提示的。就算绕过这个限制,你修改的也只是临时变量,不会影响原数组里的字符,毫无意义。

正确的基础实现方案

下面是修复后的代码,用基础技术实现,处理了字母的大小写循环偏移(比如Z偏移3变成C,z变成c),同时保留非字母字符不变:

static void Main(string[] args) {
    Console.WriteLine("Welcome to the Caesarian Cipher program");
    Console.WriteLine("Please, enter a word.");
    string word = Console.ReadLine();
    char[] letters = word.ToCharArray();

    // 遍历每个字符执行偏移
    for(int i = 0; i < letters.Length; i++) {
        // 只对字母字符做偏移,非字母保持原样
        if (char.IsLetter(letters[i])) {
            char original = letters[i];
            char shifted = (char)(original + 3);

            // 处理大写字母的循环偏移(比如Z+3=C)
            if (char.IsUpper(original) && shifted > 'Z') {
                shifted = (char)(shifted - 26); // 26是英文字母总数
            }
            // 处理小写字母的循环偏移(比如z+3=c)
            else if (char.IsLower(original) && shifted > 'z') {
                shifted = (char)(shifted - 26);
            }

            // 把偏移后的字符存回数组
            letters[i] = shifted;
        }
    }

    // 输出完整的加密字符串
    Console.WriteLine("Encrypted result: " + new string(letters));
    Console.ReadKey();
}

代码要点说明

  • 用char.IsLetter判断是否为字母,避免对数字、符号等非字母字符做错误偏移。
  • 针对大小写字母分别处理循环偏移:当偏移后的字符超出字母范围时,减去26(英文字母总数)回到字母表开头。
  • 修改的是数组中的letters[i](即字符本身),而不是循环索引变量i。
  • 最后将字符数组转回字符串输出,而不是逐个打印单个字符,这样能得到完整的加密结果。

如果你想用foreach循环实现

foreach不能直接修改原数组的元素,但可以构建一个新的字符集合来存储加密后的结果:

static void Main(string[] args) {
    Console.WriteLine("Welcome to the Caesarian Cipher program");
    Console.WriteLine("Please, enter a word.");
    string word = Console.ReadLine();
    List<char> shiftedChars = new List<char>();

    foreach(char c in word) {
        if (char.IsLetter(c)) {
            char shifted = (char)(c + 3);
            if (char.IsUpper(c) && shifted > 'Z') shifted -=26;
            else if (char.IsLower(c) && shifted > 'z') shifted -=26;
            shiftedChars.Add(shifted);
        } else {
            shiftedChars.Add(c);
        }
    }

    Console.WriteLine("Encrypted result: " + new string(shiftedChars.ToArray()));
    Console.ReadKey();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:48:10