【字符串问题】字符串压缩(将原来的字符串转化为字符串里的字符+该字符串出现的次数)
2013-09-15 16:01:14
字符串压缩,将原来的字符串转化为字符串里的字符+该字符串出现的次数,如
输入:12334222
输出:1121324123
可借助于sprintf函数实现。
下面用到了该函数的几个用法:
把整数打印到字符串中
spritnf 在大
多数场合可以替代
itoa。如:
//把整数123 打印成一个字符串保存在s 中。
sprintf(s, "%d", 123); //产生"123"
sprintf 的格式控制串中既然可以插入各种东西,并最终把它们“连成一串”,自然也就能够连接字符串,从而在许多场合可以替代 strcat,但 sprintf 能够一次连接多个字符串(自然也可以同时 在它们中间插入别的内容,总之非常灵活)。比如:
char* who = "I";
char* whom = "CSDN";
sprintf(s, "%s love %s.", who, whom); //产生:"I love CSDN. "
在下后面的代码中,用
sprintf(times,"%d",count); sprintf(pOutStr,"%s%c%s",pOutStr,tmpChar,times);
将输出字符串与下一个字符以及该字符出现的次数连接起来。
代码(测试暂未发现问题,欢迎交流指正!):
1 #include <iostream> 2 #include <cassert> 3 using namespace std; 4 5 const size_t MAXDIGIT = 10; 6 7 //字符串压缩 8 void StringCompress(char *pInStr,char *pOutStr) 9 { 10 assert(pInStr != NULL && pOutStr != NULL); 11 12 size_t len = strlen(pInStr); 13 char *pInCur = pInStr; 14 15 char tmpChar = 0; 16 size_t count = 0; 17 char times[MAXDIGIT + 1] = ""; 18 19 while (*pInCur) 20 { 21 tmpChar = *pInCur; 22 count = 0; 23 24 while (*pInCur && *pInCur == tmpChar) 25 { 26 ++count; 27 ++pInCur; 28 } 29 30 sprintf(times,"%d",count); 31 sprintf(pOutStr,"%s%c%s",pOutStr,tmpChar,times); 32 } 33 } 34 35 void TestDriver() 36 { 37 char inStrArray[][100] = {"0123456","i am a good boy!","12334222",""}; 38 char outStrArray[][100] = {"","","",""}; 39 size_t arrayLength = 4; 40 41 char *pInStr = NULL; //注意初始化为NULL,防止使用未初始化的指针 42 char *pOutStr = NULL; 43 44 for (size_t index = 0;index < arrayLength;++index) 45 { 46 pInStr = inStrArray[index]; 47 pOutStr = outStrArray[index]; 48 cout<<"the source string is : "<<pInStr<<endl; 49 50 StringCompress(pInStr,pOutStr); 51 cout<<"the compressed string is : "<<pOutStr<<endl<<endl; 52 } 53 } 54 55 56 int main() 57 { 58 TestDriver(); 59 return 0; 60 }
测试结果:
the source string is : 0123456 the compressed string is : 01112131415161 the source string is : i am a good boy! the compressed string is : i1 1a1m1 1a1 1g1o2d1 1b1o1y1!1 the source string is : 12334222 the compressed string is : 1121324123 the source string is : the compressed string is : 请按任意键继续. . .