public member function
<string>

std::string::operator[]

      char& operator[] (size_t pos);const char& operator[] (size_t pos) const;
Get character of string
Returns a reference to the character at position pos in the string.

If pos is equal to the string length and the string is const-qualified, the function returns a reference to a null character ('\0').
If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string (which should not be modified).

Parameters

pos
Value with the position of a character within the string.
Note: The first character in a string is denoted by a value of 0 (not 1).
size_t is an unsigned integral type (the same as member type string::size_type).

Return value

The character at the specified position in the string.

If the string object is const-qualified, the function returns a const char&. Otherwise, it returns a char&.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
// string::operator[]
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for (int i=0; i<str.length(); ++i)
  {
    std::cout << str[i];
  }
  return 0;
}

This code prints out the content of a string character by character using the offset operator on str:
Test string


Complexity

Unspecified.

Iterator validity

Generally, no changes.
On some implementations, the non-const version may invalidate all iterators, pointers and references on the first access to string characters after the object has been constructed or modified.

Data races

The object is accessed, and in some implementations, the non-const version modifies it on the first access to string characters after the object has been constructed or modified.
The reference returned can be used to access or modify characters.

Exception safety

If pos is less than the string length, the function never throws exceptions (no-throw guarantee).
If pos is equal to the string length, the const-version never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
Note that using the reference returned to modify elements that are out of bounds (including the character at pos) also causes undefined behavior.

Complexity

Constant.

Iterator validity

No changes.

Data races

The object is accessed (neither the const nor the non-const versions modify it).
The reference returned can be used to access or modify characters. Concurrently accessing or modifying different characters is safe.

Exception safety

If pos is less or equal to the string length, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
Note that using the reference returned to modify elements that are out of bounds (including the character at pos) also causes undefined behavior.

See also