Program to find the kth character after decrypting a string in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the kth character after decrypting a string.

For this, we will be provided with a string that will consist of characters and numbers and integer K. Our task is to decrypt the given string and find the character at Kth position.

Example

 Live Demo

#include <cstdlib>
#include <iostream>
using namespace std;
//finding decrypted Kth character
char findKthChar(string s, int k) {
   int len = s.length();
   int i = 0;
   int total_len = 0;
   while (i < len) {
      if (isalpha(s[i])) {
         total_len++;
         if (total_len == k)
            return s[i];
         i++;
      }
      else {
         int n = 0;
         while (i < len && !isalpha(s[i])) {
            n = n * 10 + (s[i] - '0');
            i++;
         }
         int next_total_len = total_len * n;
         if (k <= next_total_len) {
            int pos = k % total_len;
            if (!pos) {
               pos = total_len;
            }
            return findKthChar(s, pos);
         }
         else {
            total_len = next_total_len;
         }
      }
   }
   return -1;
}
int main() {
   string s = "ab2c3";
   int k = 5;
   cout << findKthChar(s, k);
   return 0;
}

Output

c
raja
Published on 08-Jun-2020 14:07:28
Advertisements