Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined.
Syntax :
reference operator[] (size_type pos); const_reference operator[] (size_type pos) const; Parameters : pos - position of the character to return Return value : Reference to the requested character Exceptions : No exception is thrown
/* CPP program to access a character through
std::basic_string::operator[] */
#include <iostream> //Driver code int main()
{ //String with valid indices from 0 to 2
std::string str = "abc" ;
//Printing size of string
std::cout << "string size = " << str.size() << '\n' ;
//Accessing element at index 2
std::cout << "Element : " << str[2];
} |
Output
string size = 3 Element : c