C++ examples for STL:string
Replacing Characters in a string, erase and replace
#include <iostream> #include <string> int main(int argc, const char* argv[]) { // compiler concatenates all parts into one string std::string string1(//from ww w .j a v a 2 s .c om "qqqqqqqqqqqqqq" "\ntest test test test test" "\nthis is a test" "\nthis is another test" "\nstring test string test"); std::cout << "Original string is:\n" << string1 << std::endl << std::endl; // remove all characters from (and including) location 62 // through the end of string1 string1.erase(62); // output new string std::cout << "Original string after erase:\n" << string1 << "\n\nAfter first replacement:\n"; unsigned int position = string1.find(" "); // replace all spaces with periods while (position != std::string::npos) { string1.replace(position, 1, "."); position = string1.find(" ", position + 1); } std::cout << string1 << "\n\nAfter second replacement:\n"; position = string1.find("."); // find first period // replace all period with two semicolons while (position != std::string::npos) { string1.replace(position, 2, "xxxxx;;yyy", 5, 2); position = string1.find(".", position + 1); } std::cout << string1 << std::endl; return 0; }