Replace Pi problem on hacker blocks platform

#include<bits/stdc++.h> 
using namespace std;
void replacePi(string in,string out)
{
if(in.size()==1){
cout<<out+in<<endl;
return;
}
if(in[0]!='p'){
string ch="" + in[0];
replacePi(in.substr(1),out+ch);
}
if(in.size()>=2 && 'p'==in[0] && 'i'==in[1]){
string bc="3.14";
replacePi(in.substr(2),out +bc);
}

}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
	string s;
	cin>>s;
	replacePi(s,"");
}
}

This code is generating some weird characters in the output, what might be the problem??

Take a normal character array and terminate it with a ‘\0’ character. Prefer character arrays when you want to update characters.

1 Like

bhaiya is using string not preferred due to substr function ?
Is it because in char arrays we just have to increment the indexes.

This was most evident to me in problems where the last 2 elements have to be taken as a pair and as well as individually. In such cases substr() is really :frowning: !!

Still somehow made this code to work
#include<bits/stdc++.h>
using namespace std;

void replacePi(string in,string out)
 {
 if(in.size()==1){

cout<<out+in[0]<<"\n";
return;
  }
 if(in.size()==2 && in[0]=='p' && 'i'==in[1]){

cout<<out+in[0]+in[1]<<"\n";
return;
 }

if(in[0]=='p' && 'i'==in[1] && in.size()>2)

replacePi(in.substr(2),out +"3.14");

else
	
replacePi(in.substr(1),out +in[0]);
}

int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
	string s;
	cin>>s;
	replacePi(s,"");
}
}

My code is not even printing any garbage value or anything. Still shows wrong answer. is it because of strings, here too?

#include
#include

using namespace std;

string temp="";
string h=“3.14”;

string replacepi(string s,int st,int n){
if(st==n){
return “”;
}

if(s[st]=='p'&&s[st+1]=='i'){
    temp+=h;
    replacepi(s,st+2,n);
    }
else{
    temp+=s[st];
    replacepi(s,st+1,n);
}
return temp;

}

int main() {
int t;
cin>>t;
int i;
string s;
for(i=0;i<t;i++){
cin>>s;
cout<<replacepi(s,0,s.length())<<endl;
}
return 0;
}