std::basic_string::operator[] in C++

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
filter_none

edit
close

play_arrow

link
brightness_4
code

/* 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];
}

chevron_right


Output

string size = 3
Element : c

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.