Open In App

Accessing characters by index in a String

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




// 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;
}




/*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));
    }
}




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




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 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)


Article Tags :