Get Char from String by Index in C++

This tutorial will discuss about unique ways to get a character from string by index in C++.

Table Of Contents

Technique 1: Get character at specific index

The string class provides a member function at(). It accepts an index position as an argument, and returns a reference to the character at that position in string. If the given index position is greater than the length of string, then it will raise out_of_range exception.

We can use the string::at() to get a character from string by index position. Like this,

int index = 3;

// Get character at specific index
char ch = strValue.at(index);

Output:

Char at Index 3 is: a

It return the character at index position 3 from the string. It we try to get a character at index position i.e. out of range (greater than the size of string), then it will throw an exception. Like this,

int index = 63;

// Get character at specific index
char ch = strValue.at(index);

Output:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 63) >= this->size() (which is 10)
Aborted (core dumped)

So, always use at() function, when you are sure that the index position exists in the string, otherwise you can catch the exception to handle this kind of scenario.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string strValue = "Final Text";

    int index = 3;

    // Get character at specific index
    char ch = strValue.at(index);

    std::cout << "Char at Index " << index << " is: " << ch << "\n";
    return 0;
}

Output :

Char at Index 3 is: a

Technique 2: Using [] Operator

We can use the [] operator to access a character from string by its index position. Like, str[i] will return the reference of character at index position i from the string. But we try to get a character at index position that does not exist in the range i.e. out of range (greater than the size of string), then it will result in an undefined behaviour.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string strValue = "Final Text";

    int index = 3;

    // Get character at specific index
    char ch = strValue[index];

    std::cout << "Char at Index " << index << " is: " << ch << "\n";
    return 0;
}

Output :

Char at Index 3 is: a

Summary

Today we learned about several ways to get char from string by index in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top