I need to create a function that accepts two chars and a string and returns a string.
The function should replace all letters in the first parameter with the second
parameter.
For example, if the string passed is “How now cow” and the function replaces
all ‘o’ to ‘e’ then the new string would be: “Hew new cew”.
I know this is wrong, but how could I modify this code to work?
#include <iostream>
using namespace std;
string replace(char a, char b, string Rstring){
string Restring;
Restring= Rstring.replace( 'o', 2, 'e')
return Restring;
}
int countspace(string mystring){
int counter;
for (int i=0;i<mystring.length();i++){
if (mystring[i]== ' ')
counter++;
}
return counter;
}
std::string.replacewill not do what you want. Instead you should write your own method, it’s not too tough to do this parsing.That loop will only work in C++11 so if it doesn’t work use this insead;
You pass this a pointer to the string and the chars you want to swap. It loops over the string char by char, when you you encounter the old char you set that to replacement. The for loop uses a reference to
cso you will be changing the string in place, no need to allocate a new string or anything. If you’re not usingstd::stringthis can be done just as easily with a character array. The concept is exactly the same.