I'm just going through some textbook c++ questions and one of them is to write a function which recursively replaces all instances of a certain letter in a string with another letter. I know that there are pre-existing functions for this, but because this chapter focuses on recursion, this question insists that the solution must be recursive. So I wrote all this out in c++ and it was fine but then I read the footnote to the question and what it says is: "for the manipulation of string objects, only the methods at and length (i.e. size) are allowed as well as the operator +". whaaa? I just don't see how you could make this happen without str.substr(pos,len) but I would be thrilled if somebody could find a way. Thanks a bunch to that special someone yo.
Here's the best code my hamster brain could come up with (also a small iterative alternative commented out at the beginning).
#include <iostream>
#include <string>
using namespace std;
// iterative solution
/* string replace (string in, char from, char to) {
string res;
for (int i{0}; i < in.length(); i++) {
if (in.at(i) == from)
res += to;
else
res += in.at(i);
}
return res;
} */
// recursive solution
string replace (string in, char from, char to) {
if (in.empty())
return "";
char first{in.at(0)};
if (first == from)
return to + replace (in.substr(1), from, to);
else
return in.at(0) + replace (in.substr(1), from, to);
}
int main () {
string in;
char from, to;
cout << "Word: ";
cin >> in;
cout << "from: ";
cin >> from;
cout << "to: ";
cin >> to;
cout << in << " --> " << replace (in, from, to) << '\n';
return 0;
}
Just provide a default argument that keeps track of the index:
string replace(string in, char from, char to, int i = 0)
{
if (i == in.length())
return in;
if (in.at(i) == from)
in.at(i) = to;
return replace(in, from, to, i + 1);
}
Here's a demo.
This only uses at()
, and length()
, and doesn't even use +
.
Also, avoid using namespace std;
, it's bad practice.