The C++ insert() program example part I
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: Inserts an element or a number of elements or a range of elements into the string at a specified position using insert() in C++ programming
To show: How to use the insert() function to an element or a number of elements or a range of elements into the string at a specified position in C++ programming
// the C++ insert() example part I
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
// inserting a C-string at a given position
basic_string <char> str1("e insert() testing");
const char *cstr1 ="Th";
cout<<"str1 = "<<str1<<endl;
cout<<"cstr1 = "<<cstr1<<endl;
str1.insert(0, cstr1);
cout<<"Operation: str1.insert(0, cstr1)"<<endl;
cout<<"Inserting a C-string at position 0 is: "<<str1<<endl;
cout<<endl;
// inserting a C-string at a given position for a specified number of elements
basic_string <char> str2("Test");
const char *cstr2 ="ing an insert()";
cout<<"str2 = "<<str2<<endl;
cout<<"cstr2 = "<<cstr2<<endl;
str2.insert(4, cstr2, 15);
cout<<"Operation: str2.insert(4, cstr2, 15)"<<endl;
cout<<"Inserting a C-string at the end is: "<<str2<<endl;
cout<<endl;
// inserting a string at a given position
basic_string <char> str3(" the insert()");
string str4("Testing");
cout<<"str3 = "<<str3<<endl;
cout<<"str4 = "<<str4<<endl;
str3.insert(0, str4);
cout<<"Operation: str3.insert(0, str4)"<<endl;
cout<<"Inserting string at position 0 is: "<<str3<<endl;
cout<<endl;
// inserting part of a string at a given position
basic_string <char> str5("Testing ");
string str6(" the insert()");
cout<<"str5 = "<<str5<<endl;
cout<<"str6 = "<<str6<<endl;
str5.insert(7, str6, 4, 9);
cout<<"Operation: str5.insert(7, str6, 4, 9)"<<endl;
cout<<"Inserting part of a string at position 9 is: "<<str5<<endl;
return 0;
}
Output example:
str1 = e insert() testing
cstr1 = Th
Operation: str1.insert(0, cstr1)
Inserting a C-string at position 0 is: The insert() testing
str2 = Test
cstr2 = ing an insert()
Operation: str2.insert(4, cstr2, 15)
Inserting a C-string at the end is: Testing an insert()
str3 = the insert()
str4 = Testing
Operation: str3.insert(0, str4)
Inserting string at position 0 is: Testing the insert()
str5 = Testing
str6 = the insert()
Operation: str5.insert(7, str6, 4, 9)
Inserting part of a string at position 9 is: Testing insert()
Press any key to continue . . .