首页 > 解决方案 > 初学c#任务报错

问题描述

所以我正在创建一个程序,它将接收一个字符串并将其输出为每个使用的字符以及一行中有多少个字符。例如“aaarrrgggghhhh”将输出:a3r3g4h4。我当前的程序有一个错误,它不会输出最后一个字符,谁能帮我找出错误,谢谢!

public static void Main()
{
    int count = 1;
    Console.Write(" Input a string : ");
    string str1 = Console.ReadLine();
    for (int i = 0; i < str1.Length-1; i++)
    {
        if (str1[i] == str1[i+1] )
        {
            count++;
        }
        else
        {
            Console.Write(Convert.ToString(str1[i]) + count);
            count = 1;
        }
    }
    Console.ReadKey();
}

标签: c#stringloopsfor-loopif-statement

解决方案


尝试这个:

        Console.Write("Input a string: ");
        var input = Console.ReadLine();
        if (string.IsNullOrWhiteSpace(input)) return;

        var currentChar = input[0];
        var occurrence = 1;
        var result = string.Empty;

        for (var index = 1; index < input.Length; index++)
        {
            if (input[index] != currentChar)
            {
                result += $"{currentChar}{occurrence}";
                occurrence = 0;
                currentChar = input[index];
            }

            occurrence++;
        }

        result += $"{currentChar}{occurrence}";

        Console.WriteLine(result);
        Console.ReadLine();

推荐阅读