In: Computer Science
Please Write Code in C++ and include the correct #include <header> and not a catchall such as bits/stdc:
Write a recursive, string-valued function, replace, that accepts a string and returns a new string consisting of the original string with each blank replaced with an asterisk (*)
Replacing the blanks in a string involves:
Code
#include<iostream>
using namespace std;
string rec(string s,int c)
{
if(s.empty() && c==0) //if c==0 then string is processing for first time and empty() defines empty string hence return nothing
return "Nothing";
if(s.empty() && c!=0) //c!=1 defines non empty string passed hence no need to add "nothing" at end hence return ""
return "";
c++;
if(s[0]==' ')
return "*"+rec(s.substr(1),c);
return s[0]+rec(s.substr(1),c);
}
int main()
{
string s;
cout<<"Enter the string:\n";
getline(cin,s); //get input string from user
int c=0; //helps to decide return nothing or ""
string res=rec(s,c);
cout<<"Modified string is:\n"<<res;
return 0;
}
Terminal Work
.