Open In App

string at() in C++

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::string::at() in C++ is a built-in function of std::string class that is used to extract the character from the given index of string. In this article, we will learn how to use string::at() in C++.

Syntax

str.at(idx)

Parameters

  • idx: Index at which we have to find the character.

Return Value

  • Returns the character at the given index of the string.
  • If the given index is less than 0 or greater than equal to the length of string, then it throws an out_of_range exception.

Example of string::at()

C++
// C++ Program to show, how to use string::at()
// for extracting the character from given index
#include <bits/stdc++.h>
using namespace std;

int main() {
    string str("GeeksForGeeks");

    // Extracting the character of 0th index
    cout << str.at(0) << endl;

    // Extracting the character of 5th index
    cout << str.at(5) << endl;

    // Extracting the character of 9th index
    cout << str.at(9) << endl;

    return 0;
}

Output
G
F
e

Time Complexity: O(1)
Auxiliary Space: O(1)


 



Next Article
Practice Tags :

Similar Reads