c语言——把abbccc压缩成a2b3c

如题所述



题目描述(40分):  通过键盘输入一串小写字母(a~z)组成的字符串。
                    请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,
                    并输出压缩后的字符串。 
                    
压缩规则:  1. 仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc".  
            2. 压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"   
            
要求实现函数:   void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);   
【输入】 pInputStr:  输入字符串           lInputLen:  输入字符串长度          
【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;   
【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出  

示例   输入:“cccddecc”   输出:“3c2de2c” 
       输入:“adef”     输出:“adef” 
       输入:“pppppppp” 输出:“8p”
*/

#include <stdio.h>

#define LEN 1000

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
{
     char c;
     int count = 1,index = 0;
     int i=0;
     
     c = pInputStr[0];
     for(i=1; i<lInputLen; i++)
     {
             if(pInputStr[i] == c)
             {
                      count++;       
             }
             else
             {
                 if(count == 1)
                 {
                          pOutputStr[index++] = c;
                 }
                 else
                 {
                     pOutputStr[index++] = count + '0';
                     pOutputStr[index++] = c;
                 }
                 count =1;
                 c = pInputStr[i];
             }
     }
     
     if(c != pInputStr[index-1])
     {
          if(count == 1)
          {
                   pOutputStr[index++] = c;
          }
          else
          {
               pOutputStr[index++] = count + '0';
               pOutputStr[index++] = c;
          }
     }
     
     pOutputStr[index] = '\0';
}

int main()
{
    char pInputStr[LEN],pOutputStr[LEN];
    scanf("%s",pInputStr);
    
    stringZip(pInputStr, strlen(pInputStr), pOutputStr);
    printf("%s\n",pOutputStr);
    system("pause");
    return 0;
}

这个的原题应该是上面的注释部分,我已经测试过了,DEVCPP环境下测试的,你看看有什么疑问可以继续追问,望采纳!

追问

把a2b3c解压缩成abbccc,怎么做呢

追答

这个暂时时间比较近没办法帮你写了,不过可以给你思路(不行再告诉我,我帮你看看):
1、函数的参数可以考虑个上面的是一样的:const char *pInputStr, long lInputLen, char *pOutputStr
2、对输入的字符串分析,遇到数字字符转换成数,这样可以得到后面的字符数目,如a2b30c可以采用一个计数器count=0;读到a为非数字字符,直接将其赋值给输出字符串,读到2
为数字字符,count = count*10+‘2’-‘0’;读到字符b时对count计数,赋值给输出字符串,直到count为0为止;其他的依次类推

温馨提示:答案为网友推荐,仅供参考