首页 > 解决方案 > C# 字符串压缩

问题描述

我需要制作 amethod作为string参数返回 astring作为结果

public static string Compress(string test){}

无法真正用文字描述此方法需要做什么,所以这里是输入/输出示例:

输入参数:ssdwwwweehh

输出结果:s2d1w4e2h1

我试过的是这样的:

static string Compression(string test)
    {
        string result = string.Empty;

        for (int i = 0; i < test.Length; i++)
        {

            
            int counter = 1;
            
            for (int j = i+1; j < test.Length; j++)
            {
                if (test[i] == test[j])
                {
                    counter++;
                }
                else
                {
                    i = j-1;
                    break;
                }      
            }

            result += test[helper] + counter.ToString();
        }

        return result;
    }

我得到的结果是s2d1w4e2h2h1。所以我想问题是当我的方法到达给定单词的末尾时。我该如何处理/解决这个问题?此外,我愿意接受有关更好解决方案的建议,因为我不确定这是解决它的最佳方法。

标签: c#loops

解决方案


好的,我猜对了。int helper = i;由于在第二个循环中i丢失,在声明中必须执行。 forelse

回答:

static string Compression(string test)
        {
            string result = string.Empty;

            for (int i = 0; i < test.Length; i++)
            {

                int helper = i;
                int counter = 1;
                
                for (int j = i+1; j < test.Length; j++)
                {
                    if (test[i] == test[j])
                    {
                        counter++;
                        if(j == test.Length - 1)
                        {
                            return result += test[helper] + counter.ToString();
                        }  
                    }
                    else
                    {
                        i = j-1;
                        break;
                    }      
                }

                result += test[helper] + counter.ToString();
            }

            return result;
        }

推荐阅读