Answer to Question #31717 in C++ for MANMOHAN SHARMA

Question #31717
Write a function for replacing all occurrences of a specified string value with another value. For Example: “I love chatting with friends.” Replace: “friends”, “girls”. It should return: “I love chatting with girls
1
Expert's answer
2013-06-11T11:41:40-0400
#include <iostream>
#include <string>

using namespace std;

string replaceValue(string a, string b, string c)
{
char tmp = ' ';
string r=a;
std::size_t found_begin = a.find(b);
std::size_t found_end = 0;
for (int i = found_begin; i < a.size(); ++i)
if(a[i] == tmp)
{
found_end = i - 1;
break;
}
if (found_end == 0) found_end = a.size() - 1;
r.replace(found_begin,found_end-found_begin + 1,c);
return r;
}

int main()
{
{
std::string a = "I love chatting with friends";
std::string b = "friends";
std::string c = "girls";
std::string r = replaceValue(a,b,c);
cout << r << endl;
}

{
std::string a = "I love chatting with friends";
std::string b = "chatting";
std::string c = "meeting";
std::string r = replaceValue(a,b,c);
cout << r << endl;
}
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS