【问题标题】:Why isn't the last character of my RLE not displaying?为什么我的 RLE 的最后一个字符不显示?
【发布时间】: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

标签: c# run-length-encoding


【解决方案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();

【讨论】:

  • 不确定 temp2 在做什么,但我为您格式化了它,以便它遍历所有内容
  • Temp2 将字符 i+1 存储在数组中,然后我比较这两个字符是否相同
猜你喜欢
  • 1970-01-01
  • 2020-07-05
  • 2021-05-18
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
相关资源
最近更新 更多