C++ Standard Library C++ STL Library

C++ <string> - operator[] Function



The C++ string::operator[] function returns a reference to the character of the string at the specified position. If the specified position is not within the bounds of valid characters in the string, the function does not throw any exception.

Note: The string::operator[] function produces the same result as string::at function, except string::at do check the specified position against bounds of valid characters in the string.

Syntax

char& operator[] (size_t n);
const char& operator[] (size_t n) const;
char& operator[] (size_t n);
const char& operator[] (size_t n) const;

Parameters

n Specify position of the character in the string.

Return Value

The character at the specified position in the string.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::operator[] function returns a reference to the character of the string at the specified position.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string str = "AlphaCodingSkills";

  cout<<"str contains: ";
  for(int i = 0; i < str.size(); i++)
    cout<<" "<<str[i];

  return 0;
}

The output of the above code will be:

The string contains: A l p h a C o d i n g S k i l l s

❮ C++ <string> Library