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

C#中索引超出长度时循环遍历字符串或数组的实现方法

解决索引越界并循环遍历的方法

核心思路是用**取模运算(%)**获取有效索引:对于长度为N的集合,任何整数key对N取模后,结果都会落在0到N-1的范围内,刚好对应集合的有效索引,实现循环遍历的效果。

针对数组alflist的解决方案

把你的代码改成:

// 计算有效索引:取模数组长度
int validIndex = Encryption.key % alflist.Length;
string output = alflist[validIndex];

比如你提到的Encryption.key=30,30 % 26 = 4,对应数组索引4的元素"e",完全符合需求。

针对字符串alf的解决方案

字符串可直接通过索引访问单个字符,无需用Substring(当然用也可行),同样用取模处理:

int validIndex = Encryption.key % alf.Length;
// 直接取字符转成字符串
string output = alf[validIndex].ToString();

// 若坚持用Substring,写法如下:
string output = alf.Substring(validIndex, 1);

额外说明:处理负数key的情况

如果Encryption.key可能为负数(比如反向循环场景),可先把余数转正,避免出现负索引:

int validIndex = (Encryption.key % alflist.Length + alflist.Length) % alflist.Length;

比如key=-1时,(-1 %26 +26)%26 =25,对应最后一个元素"z",实现反向循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:29:59