c# - 为什么我的 RLE 的最后一个字符不显示?
问题描述
我是 C# 新手,并尝试编写自己的简单方法来对字符串进行运行长度编码。除了最后一个字母,它工作正常,因为最后一个字母不会显示。我的逻辑有什么问题?
namespace RunLengthEncoding
{
class Program
{
static void Main(string[] args)
{
string tobesorted;
string encoded = "";
int temp1, temp2;
int same = 1;
Console.WriteLine("Please enter the string you want to be sorted");
tobesorted = Console.ReadLine();
tobesorted = tobesorted.ToUpper();
tobesorted = tobesorted.Replace(" ", string.Empty);
char[] tbsarray = tobesorted.ToCharArray();
for (int i =0; i < tbsarray.Length-1; i++)
{
temp1 = tbsarray[i];
temp2 = tbsarray[i + 1];
if (temp1==temp2)
{
same++;
}
else
{
encoded = encoded + tbsarray[i];
encoded = encoded + Convert.ToString(same);
same = 1;
}
if ((tbsarray.Length-2 == i))
{
encoded = encoded + tbsarray[i] + Convert.ToString(same);
Console.WriteLine(encoded);
}
}
Console.WriteLine(encoded);
Console.ReadLine();
}
}
}
解决方案
string tobesorted;
string encoded = "";
int temp1
int same = 1;
Console.WriteLine("Please enter the string you want to be sorted");
tobesorted = Console.ReadLine();
tobesorted = tobesorted.ToUpper();
tobesorted = tobesorted.Replace(" ", string.Empty);
char[] tbsarray = tobesorted.ToCharArray();
for (int i = 0; i < tbsarray.Length; i++)
{
temp1 = tbsarray[i];
encoded = encoded + tbsarray[i];
encoded = encoded + Convert.ToString(same);
same = 1;
if ((tbsarray.Length - 2 == i))
{
encoded = encoded + tbsarray[i] + Convert.ToString(same);
Console.WriteLine(encoded);
}
}
Console.WriteLine(encoded);
Console.ReadLine();
推荐阅读
- python - 如何在 python 上为 tkinter 编写菜单,以便用户只能选择一个选项?
- python - 可以在 Django 中为大型非本地文件流式传输 zip?
- c - strcmp 返回 10 即使字符串相同
- ssis - SSISDB 2019 脚本组件为空白
- bash - 在ansible中转义特殊字符
- django - 如果在 Celery 中将 retry_backoff 设置为 True,max_retries 和 retry_backoff_max 是什么意思?
- postgresql - Postgres:带有可选“WHERE”参数的函数
- php - 如何在php中优先考虑rabbitmq消息?
- java - 使用 iText 签名字段(数字签名与电子签名图像) - 阅读
- java - 根据对象中的变量名而不是字符串正则表达式在springboot中屏蔽敏感数据