C++ Standard Library C++ STL Library

C++ <string> - begin() Function



The C++ string::begin function returns 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 example below, the string::begin function returns the iterator pointing to the first character of the string called str.

#include <iostream>
#include <string>

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

  it = str.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 str = "Learn C++";
  string::iterator it;

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

  return 0;
}

The output of the above code will be:

L e a r n   C + + 

❮ C++ <string> Library