Mega Code Archive

 
Categories / C++ / Data Type
 

Insert, search, and replace in strings

#include <iostream> #include <string> using namespace std; string stringObject1 = "As 111 555 ...",               stringObject2 = "number "; int main() {    int pos = 0;    cout << "stringObject1 : " << stringObject1 << endl;    cout << "\nInserting in string: " << stringObject2 <<""<< endl;    pos = stringObject1.find("555");    if( pos != string::npos )       stringObject1.insert(pos,stringObject2);    cout << "stringObject1 : " << stringObject1 << endl;                 cout << "\nTo erase remaining characters behind 555:"         << endl;    pos = stringObject1.find("555");    if( pos != string::npos )       stringObject1.erase(pos + 3);    cout << "stringObject1 : " << stringObject1 << endl;                 cout << "\nTo replace 111 by 222:"         << endl;    pos = stringObject1.find("111");    if( pos != string::npos )       stringObject1.replace(pos, 4, "222");    cout << "stringObject1 : " << stringObject1 << endl;                 return 0; }