Hellp My Code!!!! Doesnt Work!!
Code:
#include "iostream"
#include "string"
using namespace std;
void search_and_replace(char *text, char *search, char *replace);
int main()
{
char text[256] = "You can find and replace any part of this line using this program.";
char originalText[256];
cout << "Your text is " << endl;
cout << text << endl << endl;
strcpy(originalText, text);
cout << "search_and_replace(text, \"find\", \"search\")" << endl;
search_and_replace(text, "find", "search");
cout << text << endl << endl;
strcpy(text, originalText);
cout << "search_and_replace(text, \"and\", \"&\")" << endl;
search_and_replace(text, "and", "&");
cout << text << endl << endl;
// ...
strcpy(text, originalText);
cout << "search_and_replace(text, \"this line\", \"a sentence\")" << endl;
search_and_replace(text, "this line", "a sentence");
cout << text << endl << endl;
strcpy(text, originalText);
cout << "search_and_replace(text, \"this\", \"the\")" << endl;
search_and_replace(text, "this", "the");
cout << text << endl << endl;
return 0;
}
void search_and_replace(char *text, char *search, char *replace)
{
char *pStart;
char *pTemp;
char *pOriginal;
pOriginal = text;
if ( (pStart = strstr(text, search)) == NULL )
{
cout << "No search string found." << endl;
return;
}
pTemp = new char[(pStart-text)+strlen(replace)+(strlen(text)-strlen(search))+1];
strncpy(pTemp, text, (pStart-text));
pTemp[pStart-text] = '\0';
strcat(pTemp, replace);
text += (pStart-text)+strlen(search);
strcat(pTemp, text);
text = pOriginal;
strcpy(text, pTemp);
delete pTemp;
}