strchr() Function

The strchr() function in C locates the first occurrence of a specified character within a given string. It searches the string and returns a pointer to the matching character, which allows for further manipulation of the substring starting at that point.


Syntax of strchr()

</>
Copy
char *strchr(const char *str, int c);

Parameters

ParameterDescription
const char *strThe C string to be scanned.
int cThe character to be located, passed as its int value.

Return Value

The function returns a pointer to the first occurrence of the character in the string. If the character is not found, a null pointer is returned.

Notes

The terminating null-character is considered part of the C string, so strchr() can also be used to locate the end of the string. This function is defined in the header file string.h.


Examples for strchr()

Example 1: Finding a Character in a String

This example demonstrates how to search for a specific character in a string and print the substring starting from that character.

Program

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

int main() {
    char text[] = "Hello, World!";
    char *result;

    // Search for the character 'W' in the string
    result = strchr(text, 'W');

    if (result != NULL) {
        printf("Found substring: %s\n", result);
    } else {
        printf("Character not found.\n");
    }
    return 0;
}

Output:

Found substring: World!

Example 2: Handling a Character Not Present

This example shows the behavior of strchr() when the searched character is not present in the string.

Program

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

int main() {
    char text[] = "Hello, World!";
    char *result;

    // Attempt to search for a character that does not exist in the string
    result = strchr(text, 'z');

    if (result != NULL) {
        printf("Found substring: %s\n", result);
    } else {
        printf("Character not found.\n");
    }
    return 0;
}

Output:

Character not found.