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

2.5

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

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.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2.5 Average Difficulty : 2.5/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.