Get a Character at a Specific Index in a String in C
In C, you can retrieve a character from a specific index in a string using array indexing, pointer arithmetic, or functions like strchr()
. Since strings in C are character arrays terminated by a null character (\0
), you can access individual characters using their index position, starting from 0.
Examples to Get a Character at a Specific Index
1. Using Array Indexing other Get Character at a Given Index
In this example, we will access a character at a given index using array indexing. Since strings in C are character arrays, we can access any character directly using square brackets ([]
).
main.c
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int index = 7; // Getting the character at index 7
char character = str[index];
printf("Character at index %d: %c\n", index, character);
return 0;
}
Explanation:
- We declare a string
str[] = "Hello, World!"
. - We set
index = 7
, which corresponds to the character ‘W’. - We retrieve the character using
char character = str[index];
. - We print the character using
printf()
.
Output:
Character at index 7: W
2. Using Pointer Arithmetic
In this example, we will access a character at a specific index using pointer arithmetic. Instead of using array indexing, we use a pointer to navigate through the string.
main.c
#include <stdio.h>
int main() {
char str[] = "Programming";
int index = 4; // Getting the character at index 4
char character = *(str + index);
printf("Character at index %d: %c\n", index, character);
return 0;
}
Explanation:
- We declare a string
str[] = "Programming"
. - We define
index = 4
, which corresponds to ‘r’. - We use pointer arithmetic to retrieve the character:
*(str + index)
. - The character is printed using
printf()
.
Output:
Character at index 4: r
3. Using strchr()
Function
In this example, we will use the strchr()
function to find the character at a specific index by iterating through the string.
main.c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "AppleBanana";
int index = 5;
char *ptr = strchr(str, str[index]);
if (ptr) {
printf("Character at index %d: %c\n", index, *ptr);
} else {
printf("Character not found!\n");
}
return 0;
}
Explanation:
- We declare the string
str[] = "AppleBanana"
. - We set
index = 5
, which corresponds to ‘o’. - We use
strchr()
to find the first occurrence ofstr[index]
. - We check if the pointer is valid and print the character.
Output:
Character at index 5: B
Conclusion
In this tutorial, we explored different ways to get a character at a specific index in a string in C:
- Array Indexing: The simplest method using square brackets (
[]
). - Pointer Arithmetic: Accessing characters using memory addresses.
strchr()
Function: Finding a character’s occurrence.