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

</>
Copy
#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:

  1. We declare a string str[] = "Hello, World!".
  2. We set index = 7, which corresponds to the character ‘W’.
  3. We retrieve the character using char character = str[index];.
  4. 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

</>
Copy
#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:

  1. We declare a string str[] = "Programming".
  2. We define index = 4, which corresponds to ‘r’.
  3. We use pointer arithmetic to retrieve the character: *(str + index).
  4. 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

</>
Copy
#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:

  1. We declare the string str[] = "AppleBanana".
  2. We set index = 5, which corresponds to ‘o’.
  3. We use strchr() to find the first occurrence of str[index].
  4. 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:

  1. Array Indexing: The simplest method using square brackets ([]).
  2. Pointer Arithmetic: Accessing characters using memory addresses.
  3. strchr() Function: Finding a character’s occurrence.