Using strings
#include <iostream>
#include <string>
using namespace std;
string replaceSubstring(string, string, string);
int main()
{
string string1 = "the dog jumped over the fence",
string2 = "the",
string3 = "that",
newString;
cout << "This program will replace a keyword in a sentence with another word.\n\n\n";
cout << "Our sentence: " << string1 << endl;
cout << "Replace \"" << string2 << "\" with \"" << string3 << "\"\n\n" << endl;
cout << "Calling function ...\n\n";
newString = replaceSubstring(string1, string2, string3);
cout << newString << endl;
return 0;
}
string replaceSubstring(string string1, string string2, string string3)
{
int position = 0;
int origLength = string2.length();
position = string1.find(string2,position);
while(position >= 0) {
string1.erase(position, origLength);
string1.insert(position, string3 );
position = string1.find(string2, position);
}
return string1;
}
Now I'm attempting to do this via a char array and kinda of stuck on the process. Obviously, declare the char arrays, allow a pointer to be returned from the function. My problem is I'm more than likely over complicating the search and replace. Would I need to dynamically allocate a new array and strcpy? Looking for thoughts and suggestions on how to tackle.