Recursive program to insert a star between pair of identical characters in C++

Given a string str1 as input. The goal is to insert a ‘*’ between a pair of identical characters in the input string and return the resultant string using a recursive approach.

If the input string is str1= "wellness" then output will be "wel*lnes*s"


Input − str1="happiness"

Output − String after adding * : hap*pines*s

Explanation − Adding * between pairs pp and ss will gives us resultant string hap*pines*s

Input − str1=”swimmmmingggg pooool”

Output − String after adding * : swim*m*m*ming*g*g*g po*o*o*ol

Explanation − Adding * between pairs mm, gg and oo will gives us resultant string swim*m*m*ming*g*g*g po*o*o*ol

Approach used in the below program is as follows

In this approach take string str1. In each iteration split str1 into two with the current index as the middle point. If last character of first substring is same as first character of next substring then set original string as substring 1 followed by ‘*’ followed by substring2. End recursion in case the length of substring2 is 0.

  • Take the input string as str1 and calculate its length as len.

  • Function addStar(string& s1, int i, int len1) takes s1, its length and current index as input and adds * if two pair of characters are the same..

  • Take tmp1 as substring of s1 from index 0 to i

  • Take tmp2 as a substring of s1 from index i to len1 + 1.

  • If last character of tmp1 and first character of tmp2 are equal then set s1=tmp1+’*’+tmp2.

  • Call addStar(s1, i+1, len1); for next iteration.

  • At the end print the str1 inside main.


#include <iostream>
using namespace std;
void addStar(string& s1, int i, int len1){
   string tmp1=s1.substr(0,i);
   string tmp2=s1.substr(i,len1+1);
   if (tmp2.length() == 0){
   if (tmp1[i-1] == tmp2[0]){
      s1 = tmp1 + '*' + tmp2;
   addStar(s1, i+1, len1);
int main(){
   string str1 = "aabbcccdddd";
   int len=str1.length();
   addStar(str1, 0, len-1);
   cout << "String after adding * : "<<str1 << endl;
   return 0;


If we run the above code it will generate the following Output

String after adding * : a*ab*bc*c*cd*d*d*d

Updated on: 03-Nov-2021


Kickstart Your Career

Get certified by completing the course

Get Started