The C++ insert() program example part II

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Inserting an element or a number of elements or a range of elements into the string at a specified position using insert() function in C++ programming

To show: How to an element or a number of elements or a range of elements into the string at a specified position using insert() in C++ programming part II

 

// the C++ insert() example part II

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

// inserting a number of characters at a specified position in the string

string str7("Testing the insert()?");

cout<<"str7 = "<<str7<<endl;

str7.insert(20, 4, '!');

cout<<"Operation: str7.insert(20, 4, '!')"<<endl;

cout<<"Inserting characters: "<<str7<<endl;

cout<<endl;

 

// inserting a character at a specified position in the string

string str8("Tesing the insert()");

cout<<"str8 = "<<str8<<endl;

basic_string <char>::iterator StrIter = (str8.begin() + 3);

str8.insert(StrIter, 't');

cout<<"Operation: str8.insert(StrIter, 't')"<<endl;

cout<<"Inserting missing character: "<<str8<<endl;

cout<<endl;

 

// inserts a range at a specified position in the string

string str9("First part");

string str10("Second partition");

cout<<"str9 = "<<str9<<endl;

cout<<"str10 = "<<str10<<endl;

basic_string <char>::iterator Str9Iter = (str9.begin() + 5);

str9.insert(Str9Iter, str10.begin()+6, str10.end()-4);

cout<<"Operation: str9.insert(Str9Iter, str10.begin()+6, str10.end()-4)"<<endl;

cout<<"Inserting a range of character: "<<str9<<endl;

cout<<endl;

 

// inserting a number of characters at a specified position in the string

string str11("Final insert() test");

cout<<"str11 = "<<str11<<endl;

basic_string <char>::iterator Str11Iter = (str11.begin() + 15);

str11.insert(Str11Iter, 5, 'a');

cout<<"Operation: str11.insert(Str11Iter, 5, 'a')"<<endl;

cout<<"A range of character inserted in the string: "<<str11<<endl;

 

return 0;

}

 

Output example:

 

str7 = Testing the insert()?

Operation: str7.insert(20, 4, '!')

Inserting characters: Testing the insert()!!!!?

 

str8 = Tesing the insert()

Operation: str8.insert(StrIter, 't')

Inserting missing character: Testing the insert()

 

str9 = First part

str10 = Second partition

Operation: str9.insert(Str9Iter, str10.begin()+6, str10.end()-4)

Inserting a range of character: First parti part

 

str11 = Final insert() test

Operation: str11.insert(Str11Iter, 5, 'a')

A range of character inserted in the string: Final insert() aaaaatest

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index