C++ string operator[]
Example
Get and change a character in a string with square brackets:
string txt = "Hello";
cout << txt[0] << "\n";
txt[0] = 'J';
cout << txt;
Definition and Usage
The [] operator returns the character at a given index (position) in a string. The first character has index 0, the second has index 1, and so on. You can also use it to change the character.
Unlike at(), [] does not check the index. If the index is out of range, the result is undefined (the program can crash or give wrong results).
The operator[] is defined in the <string> header file.
Tip: Learn more in the Access Strings chapter.
Syntax
string[index]
Parameter Values
| Parameter | Description |
|---|---|
| index | Required. The index (position) of the character. |
Technical Details
| Returns: | A reference to the character at the given index. You can read it or change it. |
|---|
Related Pages
Read more about strings in our String Tutorial.