简体   繁体   中英

Why isn't the last character of my RLE not displaying?

I am new to C# and tried to code my own simple method for Run Length Encoding on a string. It works fine except for the last letter because the last letter will not display. What is wrong with my logic?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM