strchr() in C - Source Code Example

In this source code example, we will see how to use the strchr() function in C programming with an example.

strchr() Function Overview

The strchr() function finds the first occurrence of a character in a string. It's part of the <string.h> header. It returns a pointer to the first occurrence of the character, or NULL if the character is not found. 

Key points: 

- Located in the <string.h> header. 

- Searches for the first occurrence of a character in a string. 

- Returns a pointer to the character or NULL if not found.

Source Code Example

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!";
    char ch = 'o';

    char *result = strchr(str, ch);
    if (result) {
        printf("Character '%c' found at position: %ld\n", ch, result - str);
    } else {
        printf("Character '%c' not found in the string.\n", ch);
    }

    return 0;
}

Output

Character 'o' found at position: 4

Explanation

1. A string str and character ch are declared.

2. The strchr() function is used to search for the first occurrence of ch in str.

3. If the character is found, the function returns a pointer to the first occurrence. We calculate the position using pointer arithmetic (result - str).

4. If the character isn't found, a message is displayed to indicate this.


Comments