面试题1字符串的压缩

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 
 4 #include <malloc.h>
 5 #include <string.h>
 6 /*
 7 功能:
 8 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
 9 压缩规则:
10 1、仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。
11 2、压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。
12 要求实现函数:
13 void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
14 【输入】 pInputStr:  输入字符串
15 lInputLen:  输入字符串长度
16 【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;*/
17 void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
18 
19 int main()
20 {
21     char inputStr[100];
22     char outputStr[100];
23 
24     memset(inputStr, '', sizeof(char) * 100);//清空操作
25     memset(outputStr, '', sizeof(char) * 100);
26 
27     gets(inputStr);
28     stringZip(inputStr, strlen(inputStr), outputStr);//数组地址 长度 最后放入的数组
29 
30     printf("%s", outputStr);
31 
32     getchar();
33 
34     return 0;
35 }
36 
37 void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
38 {
39     char cTemp;
40     int i;
41     int count = 1;
42     char tempStr[20];
43 
44     memset(tempStr, '', sizeof(char) * 20);
45 
46     for (i = 1; i <= lInputLen; i++)
47     {
48         cTemp = pInputStr[i - 1];//这里注意循环从1开始 后一个和前一个比较相等就计数
49         if (cTemp == pInputStr[i])
50         {
51             count++;
52             continue;    //结束这次循环        
53         }
54         else
55         {
56             if (count == 1)//如果还是最初的值 也就是没有相邻重复的
57             {
58                 sprintf(tempStr, "%c", cTemp);//输出到字符串
59                 //printf("%s", tempStr);
60                 //getchar();
61 
62                 strcat(pOutputStr, tempStr);
63                 memset(tempStr, '', sizeof(char) * 20);
64             }
65             else//有重复的情况
66             {
67                 sprintf(tempStr, "%d%c", count, cTemp);
68                 strcat(pOutputStr, tempStr);
69                 memset(tempStr, '', sizeof(char) * 20);
70             }
71             count = 1;
72         }
73     }
74 }
原文地址:https://www.cnblogs.com/lanjianhappy/p/6443792.html