How to get the nth character of a string in C
In this tutorial, we will learn how to get the nth character of a string in C.
In C language, strings are the array of characters, where the index of the first character is 0
, the second character is 1
etc.
Getting the nth character
To access the nth character of a string in C, we can use the square brackets []
notation by passing the character index.
Here is an example, that gets the first character G
from the following string:
#include <stdio.h>
int main() {
char name[5] = "Gowtham";
char firstCharacter = name[0];
printf("First Character is : %c", firstCharacter);
}
Output:
"G"
We can access the other characters of a string like this:
char secondCharacter = name[1];
char thirdCharacter = name[2]