Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ string::begin function is used to return the iterator pointing to the first character of the string. Please note that, Unlike the string::front function, which returns a direct reference to the first character, it returns the iterator pointing to the same character of the string.

C++ begin end

Syntax

iterator begin();
const_iterator begin() const;
iterator begin() noexcept;
const_iterator begin() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to the beginning 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 below example, the string::begin function is used to return the iterator pointing to the first character of the string called MyString.

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyString = "Learn C++";
  string::iterator it;

  it = MyString.begin();
  cout<<*it<<" ";
  it++;
  cout<<*it<<" ";
  it++;
  cout<<*it<<" ";
  return 0;
}

The output of the above code will be:

L e a

Example:

Lets see another example where string::begin function is used with string::end 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 Functions