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


The C++ string::operator[] function is used to return 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 below example, the string::operator[] function is used to return a reference to the character of the string at the specified position.

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyString = "AlphaCodingSkills";

  cout<<"MyString contains: ";
  for(int i = 0; i < MyString.size(); i++)
    cout<<" "<<MyString[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 Functions