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;
}
}
}
You may use the following:
Demo