Accessing characters by index in a String
Last Updated :
02 Jan, 2024
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++
#include <iostream>
using namespace std;
int main()
{
string s = "GfG" ;
int index = 2;
cout << s[index];
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "GfG" ;
int index = 2;
printf ( "%c" , s[index]);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s = "GfG" ;
int index = 2 ;
System.out.println(s.charAt(index));
}
}
|
Python3
s = "GfG"
index = 2
print (s[ 2 ])
|
C#
using System;
class GFG
{
static void Main()
{
string s = "GfG" ;
int index = 2;
Console.WriteLine(s[index]);
}
}
|
Javascript
let str = "GFG"
let index = 2;
console.log(str.charAt(2));
console.log(str[2]);
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...