c# - 初学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();
}
解决方案
尝试这个:
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();
推荐阅读
- emacs - 在 elisp 中迭代行或标题时如何检测缓冲区的结尾?
- mongodb - 想使用springboot将图像导入mongo
- javascript - JS 对象和 JSON 的主要区别是什么?
- javascript - 电子:如何在电子中使用可读流?
- c# - 我们如何在线更新 sharepoint 中的人员选择器字段?
- python - Tobit 回归卡方
- java - QueueClient 中长时间不活动和频繁出现 MessageLockLostException
- javascript - 如何将 AJAX 响应传递给 React 组件?
- rest - 如何使用 REST API 和 XRay for JIRA 和 Cucumber + Xray 导入测试执行结果
- node.js - 对象填充数组返回 null mongoose