replace a word in string

Apr 21, 2013 at 4:50pm
closed account (oLC9216C)
I have to replace "he" or "she" to "she or he"

1
2
3
4
5
6
7
8
9
string he("he "),she("she ");

unsigned found = line.find(he);
if (found!=std::string::npos)
line.replace(line.find(he),he.length(),"she or he");

found = line.find(she);
if (found!=std::string::npos)
line.replace(line.find(she),she.length(),"she or he");


If I type in he, it become
"she or he or he"

how can i solve it?
Apr 21, 2013 at 4:56pm
I would use an if/else statement instead of always doing both. But be careful "he " is also contained in "she ".

Apr 21, 2013 at 5:00pm
closed account (oLC9216C)
my problem is how to avoid "he" is also contained in "she"
Apr 21, 2013 at 5:06pm
Do the "she" test first then put the "he" test in an else:

Pseudo code:
1
2
3
4
5
6
if(she is found)
   replace she with your statement.
else
   if(he is found)
       replace he with your statement.

Last edited on Apr 21, 2013 at 5:06pm
Apr 21, 2013 at 5:11pm
closed account (oLC9216C)
But, if the input is "He is a boy and she is a girl."
Isn't becomes "He is a boy and he or she is a girl."?
Apr 21, 2013 at 5:13pm
The string could contain both, and multiple copies too. Could it?

What if each "she" turns into something that cannot possibly exists, say XXX, first. Then each "he" does the same. Finally, each XXX becomes she or he.
Apr 21, 2013 at 5:17pm
So what do you want it to say?

If you replace "he" or "she" with "she or he" then it will always say "she or he" .
Apr 21, 2013 at 5:28pm
closed account (oLC9216C)
"She or he is a boy and he or she is a girl."
not
"He is a boy and he or she is a girl."
Apr 21, 2013 at 5:36pm
You're really not making much sense.

What exactly is your original sentence?

What exactly are you trying to obtain for your modified sentence?

Remember C/C++ are case sensitive, "He" is not the same as "he".


Apr 21, 2013 at 5:43pm
Though this code is not good nevertheless it resolves the task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <cstring>

int main()
{
	const char *he = "he ";
	const char *she_or_he = "she or he ";
	size_t n1 = std::strlen( he );
	size_t n2 = std::strlen( she_or_he );

	std::string s( "he is a man she is a woman. No, he is a woman she is a man" );

	std::cout << s << std::endl;

	std::string::size_type pos = 0;

	while ( ( pos = s.find( he, pos ) ) != std::string::npos )
	{
		bool is_she = pos != 0 && s[pos-1] == 's';
		if ( is_she ) --pos;
		s.replace( pos, is_she ? n1 + 1 : n1, she_or_he, n2 );
		pos +=n2;
	}

	std::cout << s << std::endl;
}
Last edited on Apr 21, 2013 at 5:48pm
Topic archived. No new replies allowed.