编译环境为VC6.0:
二、题目描述(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”
个人实现代码(c):
#include <stdio.h>
#include <string.h>
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
{
if(lInputLen <= 0)
{
pOutputStr[0] = '\0';
return;
}
int outlen = 0; //输出字符串pOutputStr当前长度
for(int i = 0; i < lInputLen; ++i) //因为字符有lInputLen个所以字符下标范围为0~lInputLen-1,下标lInputLen存放'\0'
{
int cnt = 1;
while(pInputStr[i] == pInputStr[i+1])
{
++cnt;
++i;
}
if(cnt != 1)
outlen += sprintf(pOutputStr + outlen, "%d", cnt); //sprintf的返回值是当次打印到数组中的字符串长度,这句话求得pOutputStr当前总长度
outlen += sprintf(pOutputStr + outlen, "%c", pInputStr[i]);
}
}
个人实现代码(c++):
#include <iostream>#include <string>#include <sstream>using namespace std ;void stringZip ( const char * pInputStr , long lInputLen , char * pOutputStr ){string str ( pInputStr );ostringstream ostr ;while ( str . size ()){int cnt = 1 ;string :: iterator iter = str . begin ();while ( iter != str . end () - 1 ){if ( * iter == * ( iter + 1 )){++ cnt ;iter = str . erase ( iter );}elsebreak ;}if ( cnt != 1 )ostr << cnt ;ostr << * iter ;str . erase ( iter );}istringstream istr ( ostr . str ());istr >> pOutputStr ;}
贴上一个不带任何IO的:
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
{
if(lInputLen <= 0)
{
pOutputStr[0] = '\0';
return;
}
string outstr; //用来暂时存放输出字符串
for(int i = 0; i < lInputLen; ++i) //因为字符有lInputLen个所以字符下标范围为0~lInputLen-1,下标lInputLen存放'\0'
{
int cnt = 1;
while(pInputStr[i] == pInputStr[i+1])
{
++cnt;
++i;
}
if(cnt != 1)
outstr += itoa(cnt, pOutputStr, 10);
outstr += pInputStr[i];
}
outstr += '\0';
outstr.copy(pOutputStr, outstr.size());
}