Understanding Strchr() Function in C

Understanding Strchr() Function in C

3 mins read340 Views Comment
Updated on Oct 3, 2023 11:54 IST

This blog explains the strchr() Function in C programming with the help of examples. Let’s understand!

2023_03_Copy-of-Feature-Image-Templates-5.jpg

In this tutorial, we will discuss the strchr() function in C programming language that enables us to locate the initial occurrence of a specific character in a string. We will be covering the following sections: 

So, without further ado, let’s get started! 

Explore C Programming Courses

Introduction to Strchr() Function in C 

In C programming language, the strchr() function is search for a specific character in a given string. It is a built-in function that is defined in the string.h header file.  

Here is the syntax for the strchr() function: 

 
char *strchr(const char *str, int c);
Copy code

Parameters of strchr() 

The strchr() function in C takes a two arguments: 

  • The first argument str, is a pointer to the null-terminated string to be searched. 
  • The second argument, c, is the character in the string. 

Return Value of strchr() 

The strchr() function returns a pointer to the first occurrence of the character c in the string str, or a null pointer if the character is not found. If c is the null character (‘’), the function returns a pointer to the string’s terminating null character. 

C Examples of strchr() Function 

Example 1: Search first occurrence of a given character in a string 

 
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char *ptr = strchr(str, 'l');
if (ptr != NULL) {
printf("'%c' found at position %ld.\n", *ptr, ptr - str);
} else {
printf("'%c' not found.\n", 'o');
}
return 0;
}
Copy code

Output: 

'l' found at position 2.  

The above example program uses the strchr() function to search for the first occurrence of the character ‘l’ in the string “Hello, world!”. If the character is found, the program prints its position in the string (starting from 0). If the character is not found, the program prints a message indicating so.  

Example 2: Search occurrences of space character in a string 

 
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "This is a string";
char *ptr = strchr(str, ' ');
while (ptr != NULL) {
printf("Space found at position %ld.\n", ptr - str);
ptr = strchr(ptr + 1, ' ');
}
return 0;
}
Copy code

Output: 

Space found at position 4. 

Space found at position 7. 

Space found at position 9. 

In the above program, we use the strchr() function to search for the first occurrence of the space character (”) in the string “This is a string”. If the character is found, the program prints its position in the string (starting from 0). We then use the strchr() function again to search for the next occurrence of the space character, starting from the position after the previous occurrence. This process continues until no more spaces are found in the string. 

Example 3: Get the occurrence of each character in a given string 

 
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
int main() {
char str[MAX_LENGTH];
int count[256] = {0};
int length, i;
char *ptr;
printf("Enter a string: ");
fgets(str, MAX_LENGTH, stdin);
length = strlen(str);
for (i = 0; i < length; i++) {
ptr = strchr(str, str[i]);
while (ptr != NULL) {
count[str[i]]++;
ptr = strchr(ptr + 1, str[i]);
}
}
printf("\nCharacter Frequency\n");
for (i = 0; i < 256; i++) {
if (count[i] != 0) {
printf("%c %d\n", i, count[i]);
}
}
return 0;
}
Copy code

Output: 

Enter a string: Everything Everywhere All At Once 
Character	Frequency 

1 		16 

A		4 

E		4 

O		1 

c		1 

e		25 

g		1 

h		4 

i		1 

l		4 

n		4 

r		9 

t		4 

v		4 

w		1 

y		4 

In this program, we first declare a string variable str of maximum length MAX_LENGTH and an integer array count of size 256 to hold the count of each character in the string. In addition, we declare variables length and I to store the length of the string and iterate over it.

We then ask the user to enter a string using the fgets() function and store it in str. Calculate of the length of the string can be done using the strlen() function. 

Next, we use a loop to iterate over each character in the string. Inside the loop, we use the strchr() function to find the first occurrence of the current character in the string. We then use a while loop to count the total number of appearances of the character in the string by repeatedly calling strchr() with the second argument set to str[i] and the first argument set to ptr + 1 until strchr() returns NULL. 

Finally, we print out the count of each character in the string using a loop that iterates over the entire 256 ASCII character set. We only print out the characters whose count is not zero. 

Understanding the Difference Between Structure and Union in C
Understanding the Difference Between Structure and Union in C
A structure is a custom data type that holds multiple members of different data type under a single unit where union is a user defined data type that combine object...read more
Header Files in C Programming Language
Header Files in C Programming Language
The standard pre-defined library functions for the C programming language are contained in header files. By adding a header file using the C preprocessor directive “#include,” you ask for permission...read more
Operators in C programming: A Complete Tutorial
Operators in C programming: A Complete Tutorial
Here we will explore operators in C programming. Also, you will learn about classification of operators with the help of examples.

Endnotes 

In conclusion, the strchr() function examines whether the string includes the desired character or not. The function will return a pointer value if the character is present in the string. However, the function will return a null value if the character is not found. 

Hope this article was helpful for you. If you want to learn more about C programming and solidify your basics, you can explore our articles on C. 

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio