【发布时间】:2018-10-28 23:41:21
【问题描述】:
我是 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();
}
}
}
【问题讨论】:
-
您能否提供一个输入/输出示例,包括您当前得到的结果以及您的期望?
-
说你的数组中的最后一个字符与前一个不同。请注意,根据您的循环,永远不可能将
tbsarray[tbsarray.Length-1]添加到您的输出中。你可能会更好地尝试以相反的方式做事 - 有一个包含仍在等待输出的字符的变量,初始化tbsarray[0],然后从1运行你的循环到tbsarray.Length-1包括在内。 -
aaaaaabbbbbbcccccc 会给a6b6