How to compress strings. For ex: aaabbbccc -> a3b3c3

1.4k views Asked by At

I have a function which takes a string of lowercase letters (a-z) and returns a compressed string or the original string if the length of the compressed string is not less than the original. For ex: aaabbbccc -> a3b3c3, abejd -> abejd

I'm having trouble placing the integer values in my char array.

Specifically this line in my function:

newWord[k] = count;

How can I convert the integer to a character so that the function returns the correct string?

string compressString() {
int count;
int j;
char intString[32];
unsigned int k = 0;
string word;

cout << "Enter string to compress: ";
getline(cin, word);

char* newWord = new char[word.length() + 1];
for (unsigned int i = 0; i < word.length(); i++){
    count = 1;
    newWord[k] = word[i];
    k++;
    j = i;
    while (word[j + 1] == word[i]) {
        j++;
        count++;
        i = j;
    }
    if (k > word.length() - 1) {
        return word;
    }
    newWord[k] = count;
    k++;
}
string str(newWord);
delete[] newWord;
return str;
}

int main()
{
int response;
cout << "Enter test case "        << endl << endl;
cout << "0: Sort"                         << endl;
cout << "1: Get Permutations"             << endl;
cout << "2: Check Permutations"           << endl;
cout << "3: Check Permutation Palindrome" << endl;
cout << "4: Check Edits"                  << endl;
cout << "5: Compress String"              << endl << endl;
cout << "Selection: ";

cin >> response;
cin.ignore(1000, '\n');

while (response != 0) {
    switch (response) {
    case 0:
        mergeCase();
        break;
    case 1:
        permutationCase();
        break;
    case 2:
        checkPermutation();
        break;
    case 3:
        checkPalindrome();
        break;
    case 4:
        cout << checkEdits();
        break;
    case 5:
        cout << compressString();
        break;
    }
}
}
1

There are 1 answers

1
Jarod42 On

You may use the following:

std::string compress_string(const std::string& s)
{
    std::string res;
    for (auto it = s.begin(); it != s.end(); ) {
        const auto next = std::find_if(it + 1, s.end(), [&](char c) { return *it != c; });
        const auto count = next - it;
        res += *it;
        if (count != 1) {
            res += std::to_string(count);
        }
        it = next;
    }
    return res;    
}

Demo