C strchr() method

This function searches for the first occurrence of a character in a string.

Syntax:


strchr(str, c)

Parameters:

  • str: A pointer to the string to search.
  • c: The character to search for (it’s treated as an int but represents a character).

Return Value:

  • A pointer to the first occurrence of the character c in str.
  • if the character c is not found in the string then value NULL will be return.

Example:


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

int main() {
    char str[] = "My World";
    
    char *ptr = strchr(str, 'W');
    if (ptr != NULL) {
        printf("First occurrence of 'W': %s\n", ptr);  // Output:  World
    } else {
        printf("'W' not found.\n");
    }
    
    return 0;
}

Output:

First occurrence of ‘W’: World

C strchr() method – Interview Questions

Q 1: What does strchr() do?

Ans: It finds the first occurrence of a character in a string.

Q 2: What is the return type of strchr()?

Ans: Pointer to the character found or NULL.

Q 3: Which header file contains strchr()?

Ans: <string.h>.

Q 4: Is strchr() case-sensitive?

Ans: Yes, it is case-sensitive.

Q 5: What happens if the character is not found?

Ans: It returns NULL.

C strchr() method – Objective Questions (MCQs)

Q1. What does strchr() do?






Q2. What is the return type of strchr()?






Q3. Which is the correct syntax of strchr()?






Q4. What does strchr("Hello", "l") return?






Q5. What happens if the character is not found in strchr()?






Related C strchr() method Topics