Helpful Information
 
 
Category: C Programming
Replacing a character in a string

The PHP equiv is this:




$string = str_replace (" is", " was'", $string);



How would I write the code so that C++ would do the same operation?

The ANSI standard string class has a replace method with the following three arguments:

string.replace(start, length, newstring);

This means you're going to have to use the find() method to find the position of the old substring:



#include <string>
#include <iostream>
int main() {
string s = "This is the old string";
cout << s << "\n";
int start = s.find("old");
int len = string("old").size();
s.replace(start, len, "new");
cout << s << "\n";
return 0;
}



Most people write their own string class which has a replace method that works similar to how PHP does it. You can find a lot of those on the web (such as the GNU String class http://www.math.utah.edu/docs/info/libg++_19.html#SEC27). The function to replace strings like the php example is called gsub in this case.

If you're using Visual C++ or Borland C++ Builder, the string classes are called CString and AnsiString respectively. For Visual C++, the CString class has a Replace method as in:
s.Replace("old", "new");

C++ Builder has a StringReplace function that works as follows:
s = StringReplace(s, "old", "new", TReplaceFlags() << rfReplaceAll << rfIgnoreCase);

The ANSI standard string class has a replace method with the following three arguments:

string.replace(start, length, newstring);

This means you're going to have to use the find() method to find the position of the old substring:



#include <string>
#include <iostream>
int main() {
string s = "This is the old string";
cout << s << "\n";
int start = s.find("old");
int len = string("old").size();
s.replace(start, len, "new");
cout << s << "\n";
return 0;
}



Most people write their own string class which has a replace method that works similar to how PHP does it. You can find a lot of those on the web (such as the GNU String class http://www.math.utah.edu/docs/info/libg++_19.html#SEC27). The function to replace strings like the php example is called gsub in this case.

If you're using Visual C++ or Borland C++ Builder, the string classes are called CString and AnsiString respectively. For Visual C++, the CString class has a Replace method as in:
s.Replace("old", "new");

C++ Builder has a StringReplace function that works as follows:
s = StringReplace(s, "old", "new", TReplaceFlags() << rfReplaceAll << rfIgnoreCase);

I'd like to transfer "A older old wife" to "A older new wife",
i.e. with feature "whole word only", how can i do?

If your definition of "whole word" is "space delimited", then just add spaces to both sides of the parameters. Otherwise you'll need to look into C/C++ regexp libraries.










privacy (GDPR)