Is it possible in C++ to replace part of a string with another string. Basically, I would like to do this
QString string("hello $name");
string.replace("$name", "Somename");
but I would like to use the Standard C++ libraries.
Is it possible in C++ to replace part of a string with another string. Basically, I would like to do this
QString string("hello $name");
string.replace("$name", "Somename");
but I would like to use the Standard C++ libraries.
std::string has a replace method, is that what you are looking for?
You could try:
s.replace(s.find("$name"), sizeof("Somename")-1, "Somename");
I haven't tried myself, just read the documentation on find() and replace()
Yes, you can do it, but you have to find the position of the first string with string's find() member, and then replace with it's replace() member.
string s("hello $name");
size_type pos = s.find( "$name" );
if ( pos != string::npos ) {
s.replace( pos, 5, "somename" ); // 5 = length( $name )
}
If you are planning on using the Standard Library, you should really gt hold of a copy of the book The C++ Standard Library which covers all this stuff very well.
There's a function to find a substring within a string (find
), and a function to replace a particular range in a string with another string (replace
), so you can combine those to get the effect you want:
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = string.find(from);
if(start_pos == std::string::npos)
return false;
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
return true;
}
std::string string("hello $name");
replace(string, "$name", "Somename");
In response to a comment, I think replaceAll
would probably look something like this:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}