Characters and Strings: Use Bracket Notation to Find the Nth Character in a String

What is it?

C++ Use Bracket Notation to Find the Nth Character in a String is a method to access a character in a string at a specified position using bracket notation. It is a simple and efficient way of accessing individual characters in a C++ string.


Syntax

The syntax of using the bracket notation to access a character at a specified index in a string is:

string_name[index];

Where,

  • string_name: It is the name of the string variable.
  • index: Is an integer value representing the position of element (character) to be accessed. The first character is at index 0.



How to use it

To use the bracket notation, follow the below steps:

  1. Create a string variable and assign it a value.
  2. Use the bracket notation to access the character at a specified index.



Program code snippet example

#include <iostream>
#include <string>

using namespace std;

int main() {

    // Creating a string variable and assigning it a value.
    string myString = "Hello, World!";

    // Accessing the character at index 4 using the bracket notation.
    char ch = myString[4];

    cout << "Character at index 4 is: " << ch << endl;

    // Accessing an out of range index using the bracket notation.
    ch = myString[20]; // This will cause undefined behavior.

    return 0;
}

Output:

Character at index 4 is: o




Use bracket notation to find the third character in the text variable and assign it to letter.