为什么我的RLE的最后一个字符没有显示?

时间:2018-10-28 23:41:21

标签: c# run-length-encoding

我是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();

        }
    }
}

1 个答案:

答案 0 :(得分:-1)

        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();