C++ Standard Library C++ STL Library

C++ <string> - end() Function



The C++ string::end function returns the iterator pointing to the past-the-last character of the string. The past-the-last character of the string is the theoretical character that follows the last character. It does not point to any character, and hence could not be dereferenced.

C++ begin end

Syntax

iterator end();
const_iterator end() const;
iterator end() noexcept;
const_iterator end() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to the past-the-last character of the string. If the string object is constant qualified, the function returns a const_iterator, else returns an iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::end function returns the iterator pointing to the past-the-last character of the string MyString.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyString = "Learn C++";
  string::iterator it;

  it = MyString.end();
  it--;
  cout<<*it<<" ";
  it--;
  cout<<*it<<" ";
  it--;
  cout<<*it<<" ";
  return 0;
}

The output of the above code will be:

+ + C 

Example:

Lets see another example where string::end function is used with string::begin function to specify a range including all characters of the string.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyString = "Learn C++";
  string::iterator it;

  for(it = MyString.begin(); it != MyString.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

L e a r n   C + + 

❮ C++ <string> Library

5