C#自定义移位编码程序数组越界崩溃问题求助
解决Zipher编码程序数组越界问题:循环复用移位值
问题根源
当待编码单词长度超过codeShift数组的长度时,直接用字符索引i访问数组元素,会触发IndexOutOfRangeException——数组没有足够的元素供访问,自然会崩溃。
核心解决思路
用取模运算i % codeShift.Length计算当前字符对应的移位值索引。取模运算能让索引在数组长度范围内循环:当i小于数组长度时,结果就是i本身;当i超过数组长度时,会自动从0开始重新计数(比如数组长度为7,i=7时,7%7=0;i=8时,8%7=1,以此类推)。
修改后的代码示例
基于问题描述的逻辑,调整后的完整代码如下:
using System; class ZipherEncoder { static void Main() { int[] codeShift = {4, 2, 6, 3, 1, 5, 7}; // 自定义移位数组 string input = "volcanocat"; string output = EncodeZipher(input, codeShift); Console.WriteLine(output); // 输出预期结果 zqrfaspgcz } static string EncodeZipher(string input, int[] codeShift) { char[] result = new char[input.Length]; for (int i = 0; i < input.Length; i++) { // 关键修改:用取模运算循环获取移位值,避免数组越界 int shiftIndex = i % codeShift.Length; int shift = codeShift[shiftIndex]; char originalChar = input[i]; // 处理小写字母(保持大小写逻辑,可按需调整) if (char.IsLower(originalChar)) { result[i] = (char)((originalChar - 'a' + shift) % 26 + 'a'); } // 处理大写字母 else if (char.IsUpper(originalChar)) { result[i] = (char)((originalChar - 'A' + shift) % 26 + 'A'); } // 非字母字符直接保留 else { result[i] = originalChar; } } return new string(result); } }
关键代码解释
i % codeShift.Length:这行是解决问题的核心。以输入"volcanocat"(长度10)为例,codeShift长度为7:- 前7个字符(索引0-6)使用数组0-6位的移位值
- 第8个字符(索引7)用
7%7=0,取数组第0位的4 - 第9个字符(索引8)用
8%7=1,取数组第1位的2 - 第10个字符(索引9)用
9%7=2,取数组第2位的6
完全匹配你需要的"cat"部分移位规则,得到G、C、Z的结果。
测试验证
运行代码后,输入"volcanocat"会输出zqrfaspgcz,符合预期;短单词如"volcano"也能正常输出zqrfasp,不会出现任何异常。
内容的提问来源于stack exchange,提问作者Stiffeno
相关产品推荐
相关产品推荐

