# Find k’th character of decrypted string in C++

C++Server Side ProgrammingProgramming

Suppose we have one encoded string, where repetitions of substrings are represented as substring followed by count of substrings. So if the string is like ab2cd2, it indicates ababcdcd, and if k = 4, then it will return kth character, that is b here.

To solve this, we initially take empty decrypted string then decompress the string by reading substring and its frequency one by one. Then append current substring in the decrypted string by its frequency. We will repeat this process till the string has exhausted, and print the Kth character from decrypted string.

## Example

Live Demo

#include<iostream>
using namespace std;
char findKthCharacter(string str,int k) {
string decrypted = "";
string temp;
int occurrence = 0;
for (int i=0; str[i]!='\0'; ){
temp = "";
occurrence = 0;
while (str[i]>='a' && str[i]<='z'){
temp += str[i];
i++;
}
while (str[i]>='1' && str[i]<='9') {
occurrence = occurrence*10 + str[i] - '0';
i++;
}
for (int j=1; j<=occurrence; j++)
decrypted = decrypted + temp;
}
if (occurrence==0)
decrypted = decrypted + temp;
return decrypted[k-1];
}
int main() {
string str = "ab4c12ed3";
int k = 21;
cout << k << "th character in decrypted string: " << findKthCharacter(str, k);
}

## Output

21th character in decrypted string: e
Published on 17-Dec-2019 10:53:52