Open In App

Accessing characters by index in a String

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings str1 and an index, the task is to access the character at this index.

Examples:

Input: str = “hello”, index = 1
Output: e

Input: str = “GfG”, index = 2
Output: G

Accessing characters by index in a string:

Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ).

Below is the implementation for the above approach:

C++




// C++ code for the above approach:
#include <iostream>
using namespace std;
 
int main()
{
    string s = "GfG";
    int index = 2;
 
    cout << s[index];
    return 0;
}


C




// C program to access character by index
#include <stdio.h>
#include <string.h>
 
int main()
{
 
    char s[] = "GfG";
    int index = 2;
 
    printf("%c", s[index]);
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        String s = "GfG";
        int index = 2;
 
        System.out.println(s.charAt(index));
    }
}


Python3




# declaring the string
s = "GfG"
index = 2
 
# accessing the character of s at index
print(s[2])
 
# The code is modified by (omkarchorge10)


C#




using System;
 
class GFG
{
    static void Main()
    {
        string s = "GfG";
        // Define an integer 'index' with a value of 2.
        int index = 2;
        // Print the character at the specified
      // index in the string 's'.
        Console.WriteLine(s[index]);
    }
}


Javascript




// Javascript Program to access character by index
let str = "GFG"
let index = 2;
//We can do this by two ways
// Using charAt() Function
console.log(str.charAt(2));
//Using Indexes
console.log(str[2]);


Output

G

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads