通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
1. 仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc".
压缩规则:
1. 仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc".
2. 压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"
#include <iostream>
#include <string>
#define N 10
using namespace std;
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
{
if(!pInputStr)
return;
int count = 1;
int j = 0;
for(int i = 0; i < lInputLen; i ++)
{
if(pInputStr[i] == pInputStr[i + 1])
count ++;
else
{
pOutputStr[j++] = (char)(count + '0');
pOutputStr[j++] = pInputStr[i];
count = 1;
}
}
pOutputStr[j] = '\0';
}
int main()
{
char pInputStr[N];
char pOutputStr[2 * N];
cout << "please input the strings:" << endl;
cin >> pInputStr;
long lInputLen = strlen(pInputStr);
stringZip(pInputStr, lInputLen, pOutputStr);
cout << "the zip string is:" << endl;
cout << pOutputStr << endl;
system("pause");
return 0;
}