C++字符串压缩

C++ string compress

本文关键字:压缩 字符串 C++      更新时间:2023-10-16

我编写了一个程序,使用重复字符数压缩字符串。如果压缩后的字符串比原始字符串长,那么我们仍然返回原始字符串。以下是我的程序:

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] = '';
    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] = '';
    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;,则不会生成任何内容。感谢您的帮助。

变量final在代码中未初始化。当我用内存缓冲区初始化它时,无论你指向的行是否被注释掉,你的程序都会打印出所需的输出。

也许您打算使用buffer(未使用)作为final的内存,例如:

final = buffer;