strchr in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The strchr in C allows us to find the first instance of a character in a string. Essentially, strchr in C checks whether a string contains required characters. As long as a character is found within the string, the function will return a pointer value; otherwise, it will return a null value.

Syntax of strchr() Function in C

There are two parameters that the strchr in C takes: str and ch.

Parameters of strchr() Function in C

  • str: 'str' is the original string within which the character is to be found.

  • ch: An ch variable represents a character in the string str that is to be searched.

Return Value of strchr() Function in C

When a character is found within the string, strchr in C returns a pointer value; otherwise, it returns a null pointer.

Example

Output

Exception of strchr() Function in C?

There are no such exceptions defined for strchr() in C.

What is strchr() Function in C?

A strchr in C can be used to find the first instance of a specified character in a string. The function returns the pointer to the first appearance of the specified character in the given string, so displaying the string value of the pointer should show the portion of the input string that begins with the specified character.

The strchr() function works with null-ended strings. The function expects the string arguments to end with a null character (/0) that marks the end of the string.

More Examples

Program to Search a Character Using the strchr() Function and if-else Statement

The following example demonstrates how to get the first occurrence of a character in a string using the strchr() in C and if-else statement.

Output

Program to Get the Occurrence of Each Character in a Given String

With the strchr() function and a while loop in the C programming language, you can print out the occurrence of each character in a string.

Output

Conclusion

  • The strchr in C finds the first occurrence of a character in a string.
  • The strchr in C returns the first occurrence of the required character.
  • The str() in C returns NULL if the specified character is not found.