加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#语言中的字符串压缩

发布时间:2020-12-16 00:09:07 所属栏目:百科 来源:网络整理
导读:我有一个c程序,它用c语言成功地进行了字符串压缩,并且在C语言中是一个强力方法.例如,如果输入是aabccccddddddddddda,那么输出应该是a2b1c3d11a2. 我用c语言解决了这个问题,取了每个字符并计算出现次数,然后打印出那个字符和它的数量. 我试图将其转换为c#语言
我有一个c程序,它用c语言成功地进行了字符串压缩,并且在C语言中是一个强力方法.例如,如果输入是aabccccddddddddddda,那么输出应该是a2b1c3d11a2.

我用c语言解决了这个问题,取了每个字符并计算出现次数,然后打印出那个字符和它的数量.

我试图将其转换为c#语言.我想知道在c#语言中应该很容易,因为有很多字符串和char内置方法.

有没有办法我们可以在c#中使用lambda表达式或内置的string或char类型的方法在很少的行中执行此操作?

我的C代码是:

char *encode(char *src)
    {     
          int recurringLen;
          char count[MAX_RLEN];
          char *dest;
          int i,j = 0,k;
          int len = strlen(src);

         // _itoa_s(34,c,10);
          /* If all characters in the source string are different,then size of destination string would be twice of input string.
            For example if the src is "abcd",then dest would be "a1b1c1d1"
            For other inputs,size would be less than twice. 
            test for the scenarios where abababababababababababa bcos output here is a16b11.
            aabbbcccd
            */
           dest = (char *)malloc(sizeof(char)*(len*2 + 1));


          /* traverse the input string one by one */
          for(i = 0; i < len; i++)
          {

            /* Copy the first occurrence of the new character */
            dest[j++] = src[i];

            /* Count the number of occurrences of the new character */
            recurringLen = 1;     
            while(i + 1 < len && src[i] == src[i+1])
            {
              recurringLen++;
              i++;
            }   

            /* Store rLen in a character array count[] */
            sprintf_s(count,"%d",recurringLen);

            /* Copy the count[] to destination */
            for(k = 0; *(count+k); k++,j++)
            { 
              dest[j] = count[k]; 
            } 
          }  

          /*terminate the destination string */
          dest[j] = '';
          return dest;
    }

解决方法

可以通过编写扩展方法GroupSeqsBy来完成Linqy方式

string input= "aabccccdddddddddddaa";
var s = String.Join("",input.GroupSeqsBy(c => c)
                            .Select(g => g.Key.ToString() + g.Value.Count()));
public static IEnumerable<KeyValuePair<S,IEnumerable<T>>> GroupSeqsBy<T,S>(this IEnumerable<T> list,Func<T,S> keySelector)
{
    List<T> retList = new List<T>();
    S prev = keySelector(list.FirstOrDefault());
    foreach (T item in list)
    {
        if (keySelector(item).Equals(prev))
            retList.Add(item);
        else
        {
            yield return new KeyValuePair<S,IEnumerable<T>>(prev,retList);
            prev = keySelector(item);
            retList = new List<T>();
            retList.Add(item);
        }
    }
    if (retList.Count > 0)
        yield return new KeyValuePair<S,retList);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读