Skip to content
Related Articles

Related Articles

Improve Article

string at() in C++

  • Difficulty Level : Easy
  • Last Updated : 08 Jul, 2021
Geek Week

std::string::at can be used to extract characters by characters from a given string. 
It supports two different syntaxes both having similar parameters: 
Syntax 1: 
 

char& string::at (size_type idx)

Syntax 2: 
 

const char& string::at (size_type idx) const

idx : index number
Both forms return the character that has the index idx (the first character has index 0).
For all strings, an index greater than or equal to length() as value is invalid.
If the caller ensures that the index is valid, she can use operator [], which is faster.

Return value : Returns character at the specified position in the string.

Exception : Passing an invalid index (less than 0 
or greater than or equal to size()) throws an out_of_range exception.

 

CPP




// CPP code to demonstrate std::string::at
 
#include <iostream>
using namespace std;
 
// Function to demonstrate std::string::at
void atDemo(string str)
{
    cout << str.at(5);
 
    // Below line throws out of
    // range exception as 16 > length()
    // cout << str.at(16);
}
 
// Driver code
int main()
{
    string str("GeeksForGeeks");
    atDemo(str);
    return 0;
}

Output: 
 

F

 



Application

std::string::at can be used for extracting characters from string. Here is the simple code for the same. 
 

CPP




// CPP code to extract characters from a given string
 
#include <iostream>
using namespace std;
 
// Function to demonstrate std::string::at
void extractChar(string str)
{
    char ch;
 
    // Calculating the length of string
    int l = str.length();
    for (int i = 0; i < l; i++) {
        ch = str.at(i);
        cout << ch << " ";
    }
}
 
// Driver code
int main()
{
    string str("GeeksForGeeks");
    extractChar(str);
    return 0;
}

Output: 
 

G e e k s F o r G e e k s 

This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :