The C++ basic_string begin() and end() member function program example

 

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: Using the C++ basic_string begin() member function to return an iterator addressing the first element in the string and end() to return an iterator that addresses the location succeeding the last element in a string.

To show: How to use the C++ basic_string begin() and end() member function in C++ programming

 

// the C++ begin() and end() program example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

string Str1("Testing the begin() and end()"), Str2;

basic_string <char>::iterator Str1Iter;

 

// const_iterator

basic_string <char>::const_iterator Str1CIter;

 

// the following is an error because the iterator Str1CIter is const

//

// *Str1CIter = 'Z';

//

 

cout<<"Str1 string is: "<<Str1<<endl;

Str1Iter = Str1.begin();

cout<<"Operation: Str1Iter = Str1.begin()"<<endl;

cout<<"The first character of the Str1 string is: "<<*Str1Iter<<endl<<endl;

 

// using dereferenced iterator to modify a character

*Str1Iter = 'F';

cout<<"Operation: *Str1Iter = 'F'"<<endl;

cout<<"Now, the first character of the new Str1 is: "<<*Str1Iter<<endl;

cout<<"The full modified Str1 string is now: "<<Str1<<endl<<endl;

 

// for an empty string, begin() == end()

cout<<"Operation: if(Str2.begin() == Str2.end())"<<endl;

if(Str2.begin() == Str2.end())

cout<<"The Str2 string is empty."<<endl;

else

cout<<"The Str2 string is not empty."<<endl;

cout<<endl;

 

// fill up some string and retest

Str2 = "Not empty";

cout<<"Operation: Str2 = \"Not empty\""<<endl;

if(Str2.begin() == Str2.end())

cout<<"Now the Str2 string is empty."<<endl;

else

cout<<"Now the Str2 string is not empty."<<endl;

 

return 0;

}

 

Output example:

 

Str1 string is: Testing the begin() and end()

Operation: Str1Iter = Str1.begin()

The first character of the Str1 string is: T

 

Operation: *Str1Iter = 'F'

Now, the first character of the new Str1 is: F

The full modified Str1 string is now: Festing the begin() and end()

 

Operation: if(Str2.begin() == Str2.end())

The Str2 string is empty.

 

Operation: Str2 = "Not empty"

Now the Str2 string is not empty.

Press any key to continue . . .

 

 

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