字符串原地压缩
题目:将字符串原地压缩,比如"eeeeeaaaff"压缩为 "e5a3f2"。
答:
#include "stdafx.h" #include <iostream> using namespace std; //字符串原地压缩 void CompressString(char *str) { if (NULL == str) { return; } int count = 0; char *newStr = str; char ch = *str; while (*str != '\0') { if (*str != ch) { *newStr++ = ch; if (count > 1) //当字符只出现一次时,1省略不写 { *newStr++ = '0' + count; } count = 1; ch = *str; } else { count++; } str++; if (*str == '\0') { *newStr++ = ch; if (count > 1) //当字符只出现一次时,1省略不写 { *newStr++ = '0' + count; } } } *newStr = '\0'; } int _tmain(int argc, _TCHAR* argv[]) { char src[] = "eeeeeaaaff"; CompressString(src); cout<<src<<endl; cout<<endl; return 0; }
界面运行如下: