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;
}
Related examples in the same category
1. | String type class | | |
2. | A filter to remove white-space characters at the ends of lines. | | |
3. | A string demonstration: assignment, concatenate, compare | | |
4. | Demonstrate insert(), erase(), and replace(). | | |
5. | Use string: find, string::npos | | |
6. | Strings: size, iterator, count, begin and end | | |
7. | string: find( ) and rfind( ) | | |
8. | Print a name in two different formats | | |
9. | Several string operations: substr | | |
10. | String Char Indexing | | |
11. | String Find and replace | | |
12. | String Size | | |
13. | String SizeOf | | |
14. | A short string demonstration | | |
15. | String insert(), erase(), and replace() | | |
16. | string variable instead of a character array | | |
17. | Inputting Multiple Words into a String | | |
18. | Adding Strings | | |
19. | Read string from console | | |
20. | Accessing Characters In Strings | | |