word replacement program.

Hello,

I am doing a word replacement program in c++ :

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
string str[] = "This is a sample string";
char *p;
p = strstr(str,"sample");
strncpy(p,"simple",6);
cout << str;
system("pause");
return 0;

}


Errors are : Error 1 error C2075: 'str' : array initialization needs curly braces

Error 2 error C2665: 'strstr' : none of the 2 overloads could convert all the argument types




The output should be: This is a simple string.


can't we take
string str[] = "This is a sample string";

please guide me.
How many string objects do you want? Just one?
string str = "This is a sample string";

You're mixing up actual strings and char arrays. Don't do that.
Here's a way using only C++ (forget about char *)

1
2
3
4
5
6
string str = "This is a lonely phrase";
string str1 = "lonely";
string str2 = "happy";
str.replace( str.find(str1), str1.length(), str2);

cout << str;
This is a happy phrase
Last edited on
But if you want to do word replacement, rather than (dumb) string replacement, you'll need to look for whole words and then handle them.

1
2
3
4
5
6
7
string str = "This is a lonely phrase.\n\
It needs another one for company!";
string str1 = "one";
string str2 = "eight";
str.replace( str.find(str1), str1.length(), str2);

cout << str;
This is a leightly phrase.
It needs another one for company!


Andy
Last edited on
Well in that case, just stick some spaces in your find-replace strings. This will avoid substituting characters in the middle of a string.

1
2
3
4
5
6
string str = "This is a lonely phrase";
string str1 = " lonely ";
string str2 = " happy ";
str.replace( str.find(str1), str1.length(), str2);

cout << str;


If you want to find ALL occurances of that string then you can just loop it easily:
1
2
3
4
5
6
string str = "This is a lonely phrase";
string str1 = " lonely ";
string str2 = " happy ";

while (str.find(str1)!= string::npos)
  str.replace( str.find(str1), str1.length(), str2);
Last edited on
Of course, that doesn't work if you want to replace a word that is first or last on a line, or is part of a hyphenated phrase, or occurs in quotes.

I'm not suggesting you implement a version that does. More of a warning to the OP about using the code as-is. More than enough code has been contributed for him to figure out what needs to be done, I'm sure.
Agreed
Topic archived. No new replies allowed.