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

RLE压缩算法C#代码报错求助:索引越界问题及修复需求

错误排查与修复方案

问题原因

你的代码出现索引越界错误,是因为循环条件i < UserInput.Length会让i遍历到最后一个字符(索引为UserInput.Length - 1),此时i + 1等于UserInput.Length,超出了字符串的有效索引范围(字符串索引从0开始,最大索引是Length - 1)。另外,原代码还存在遗漏问题:当循环结束时,最后一组重复字符不会被输出。

修复后的RLE压缩实现

下面是修正后的代码,解决了索引越界问题,同时处理了空输入、单字符输入等边界情况:

Console.WriteLine("Enter the string you want to compress using RLE format");
string userInput = Console.ReadLine();

// 处理空输入的情况
if (string.IsNullOrEmpty(userInput))
{
    Console.WriteLine("Input string cannot be empty");
    return;
}

int repetitions = 1;
// 循环到倒数第二个字符,避免i+1越界
for (int i = 0; i < userInput.Length - 1; i++)
{
    if (userInput[i] == userInput[i + 1])
    {
        repetitions++;
    }
    else
    {
        Console.Write($"{repetitions}{userInput[i]}");
        repetitions = 1;
    }
}

// 输出最后一组字符(循环结束后剩下的最后一个或一组重复字符)
Console.WriteLine($"{repetitions}{userInput[userInput.Length - 1]}");

代码说明

  • 增加了空输入判断,避免后续逻辑出错
  • 循环条件改为i < userInput.Length - 1,确保i + 1始终是有效的索引
  • 循环结束后单独输出最后一组字符,解决原代码遗漏最后一组的问题
  • 使用Console.Write代替部分Console.WriteLine,让压缩结果连续输出(如果需要每行输出一组,可改回Console.WriteLine)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:35:22