replace and .size()

closed account (EwCjE3v7)
So I`m having trouble understanding how the string::replace() function works. What I dont get is that in the functions nothing, in the while loop, when I call replace with firstLet and firstLet +oldVal.size(). I do not understand how that replaces "tho". Shouldnt in replace "tho " with a space?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void nothing(string s, string oldVal, string newVal) 
{
	string::size_type pos = 0;

	while (s.find(oldVal, pos) != string::npos) {
		string::size_type firstLet = s.find(oldVal, pos);

		s.replace(firstLet, firstLet + oldVal.size(), newVal);
		pos += oldVal.size();

	}
	cout << s << endl;
} 

int main()
{
	nothing("tho i didnt go thru", "tho", "though");
	return 0;
} 


"tho I hate"
 ^ ^^
 | ||
 | ||
 | |Shouldnt it point here after adding the size of oldVal to firstLet? Shouldnt it replace till here?
 | |
 | Why does it replace till here?
First letter
Last edited on
The second parameter to replace is the length of the replaced string.
So the second parameter your passing is wrong and should be s.replace(firstLet, oldVal.size(), newVal);
http://www.cplusplus.com/reference/string/string/find/ writes:
Note: The first character is denoted by a value of 0 (not 1)


Other "issues":

You find twice. They should give the same result, yes?
1
2
string::size_type pos = 0;
while ( string::npos != ( pos = s.find(oldVal, pos) ) )


How many characters do you want to replace? Say, you find a 3-char word on position 1000. Will you really remove characters 1000--2002?

The 'pos' points now to the first character of newVal substring that was just inserted into the 's'. From where will continue to search?
Try with this input: oldVal="tho", newVal="tho tho"
Topic archived. No new replies allowed.