How to access a string in C++

Overview

A string in C++ is used to store text. A string variable contains a collection of characters that are enclosed by double quotes " ".

To access the characters of a string in C++, you specify in a square bracket [] the index position of the character in the string.

For instance, given a string, "Hello", the string’s first character is H and its corresponding index position is 0. The second character e has 1 as its index position.

Let’s see the code below to see how the characters of a string can be accessed.

Code

#include <iostream>
#include <string>
using namespace std;
int main() {
// creating a string
string text = "Hello";
// accessing the 0 index of the string
cout << "The index 0 character of the string is "<< text[0] << endl;
// accessing the index 1 character of the string
cout << "The index 1 character of the string is "<< text[1]<< endl;
return 0;
}

Explanation

In the code above, we create a string variable text, and return the characters of our string, which have the indexes 0 and 1, using the square bracket [] right after writing our string variable text.

Free Resources