我写了一个程序来使用重复字符的计数来压缩字符串。如果压缩字符串比原始字符串长,那么我们仍然返回原始字符串。下面是我的程序:C++字符串压缩
void stringCompress(char* src) {
char* original;
original = src;
char* rst;
rst = src;
int histogram[256];
for (int i = 0; i < 256; i++) {
histogram[i] = 0;
}
int length = 0;
while (*src != NULL) {
length++;
src++;
}
src = original;
int j = 0;
for (int i = 0; i < length; i++) {
histogram[(int) src[i]]++;
if (histogram[(int) src[i]] == 1) {
rst[j] = src[i];
j++;
}
}
rst[j] = '\0';
char* final;
rst = original;
int index = 0;
char buffer[33];
for (int i = 0; i < j; i++) {
final[index] = rst[i];
stringstream number;
number<<histogram[(int)rst[i]];
-------> //cout<<number.str()<<endl;
char* temp = new char[number.str().length()+1];
strcpy(temp, number.str().c_str());
index++;
cout<<temp<<endl;
for(int k =0 ;k<number.str().length();k++)
{
final[index]=temp[k];
index++;
}
}
final[index] = '\0';
src = original;
if (index <= length) {
for (int i = 0; i < index; i++)
cout<<final[i];
} else {
cout << src << endl;
}
}
但奇怪的是,如果我离开了COUT句子cout<<number.str()<<endl;
有(箭头指向了一句),则输出是正确的。例如,aaaabcdaa输出a6b1c1d1,aabcd输出aabcd。但是,如果我注释掉cout<<number.str()<<endl;
,则不会生成任何内容。任何帮助表示赞赏。
因为这基本上是一个C函数,无论如何,你为什么不带'printf'办呢?如果你想使用C++,你应该做到这一点(使用'std :: string's和RAII风格),只有这样才能真正带来好处。 – leftaroundabout 2012-07-15 20:13:30
作为一个方面说明,您的阅读器将无法正确读取有数字的字符串(但是,我不知道您在这里压缩哪种字符串,显然,该算法对正常文本没有用处)。 – 2012-07-15 20:13:33
我假设字符串只包含字母。其实我也不确定这个算法是用来做什么的,因为它基本上是一个面试问题。是的,现在我知道我可以使用printf而不是混合char *和字符串了。谢谢。 – Iam619 2012-07-15 20:47:22