In this C++ tutorial, you will learn how to get character present at specific index from the string using string[index] expression or string::at() function, with examples.

C++ Get Char from String at Index

string::at() function returns the char at specified index/position from the string. Or, we could also use string[index] to get the char at given index.

Syntax

The syntax to get the character at index i in the string str is

str.at(i)

The syntax to get the character at index i in the string str using array-indexing is

str[i]
ADVERTISEMENT

Examples

1. Get char in string at index=0 and index=2 using string::at(index)

In the following program, we take a string: str and print the characters present at index 0 and 2 to console by using string::at() function.

C++ Program

#include <iostream>
using namespace std;

int main() {
    string str = "apple";
    cout << "Char at index=0 is " << str.at(0) << endl;
    cout << "Char at index=2 is " << str.at(2) << endl;
}

Output

Char at index=0 is a
Char at index=2 is p
Program ended with exit code: 0

2. Get char in string at index=0 and index=2 using string[index] notation

In the following program, we take a string: str and print the characters present at index 0 and 2 to console by using string[index] function.

C++ Program

#include <iostream>
using namespace std;

int main() {
    string str = "apple";
    cout << "str[0] = " << str.at(0) << endl;
    cout << "str[2] = " << str.at(2) << endl;
}

Output

str[0] = a
str[2] = p
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to get character from string present at specific index using string[index] or string::at() function, with examples.