replace() with string

Why can't I do this using replace():
http://www.cplusplus.com/reference/algorithm/replace/

1
2
3
string str = "apple";
str.replace(str.begin(), str.end(), 'p', 'q');
cout << str;


I want to get "aqqle", but it just gives me a large string with only q's.

Try the replace_if() algorithm: http://www.cplusplus.com/reference/algorithm/replace_if/

[edit]...actually replace() works fine, too! :s
[edit again...] and replace() is not a member of std::string, so the error is at line 2 :x
Last edited on
Actually it is http://www.cplusplus.com/reference/string/string/replace/ but its behaviour is not what you expected.
closed account (S6k9GNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>
#include <iostream>
#include <algorithm> //Not part of string, use "algorithms" replace()

int main()
{
	std::string str("apple");
	std::replace(str.begin(), str.end(), 'p', 'q'); //global function
	std::cout << str;
	std::cin.ignore();
	
	return 0;
}
Last edited on
Got it. Thank you very much guys!
Topic archived. No new replies allowed.