memchr in C language

The C memchr function is a String Function, which will find the first occurrence of the character, and returns the pointer to it. This function uses its third argument to restrict the search.

The basic syntax of the memchr in C Programming language is as shown below.

void *memchr(const void *str, int c, size_t n);
  • str: A valid string
  • c: The value that you want to search inside str
  • n: The number of characters that you want to search within the search object str.

memchr in C Language Example

The memchr function used to search within the user-specified string. This program will help you to understand the memchr with multiple examples.

You have to include the #include<string.h> header before using this memchr String Function

/* memchr in C Programming Example */
 
#include <stdio.h> 
#include<string.h>

int main()
{  
   	char str[] = "C Programming Language";
   	char ch = 'L';
   	char *result;
   	char *result2;
   	
   	result = memchr(str, ch, strlen(str));
	
   	printf("\n The Final String From %c = %s", ch, result);
   	
   	result2 = memchr("Tutorial Gateway", 'G', strlen(str));
   	
   	printf("\n The Final String From %c = %s", ch, result2);
   	
   	return 0;
}
 The Final String From L = Language
 The Final String From L = Gateway

memchr in C Example 2

This program allows the user to enter his/her string and the character that they want to look at. Next, it is going to use the memchr function in C Programming to return the part of a string that starts from using the specified character.

/* memchr in C Programming Example */
 
#include <stdio.h> 
#include<string.h>

int main()
{  
   	char str[40];
   	char ch;
   	char *result;
   	
   	printf("\n Please Enter any String  : ");
	gets(str);	
	
	printf("\n Please Enter any Charcater that you want to search for  : ");
	scanf("%c", &ch);
		
   	result = memchr(str, ch, strlen(str));
	
   	printf("\n The Final String From %c = %s", ch, result);
   	
	return 0;
   	
}
memchr in C Language 2

This time we will look for non-existing character

 Please Enter any String  : Tutorial Gateway

 Please Enter any Charcater that you want to search for  : m

 The Final String From m = (null)

Although the given character exists in a string, it is returning NULL. It is because we restricted the search to the first 5 characters, and G does not exist in the first five characters. result = memchar(str, ch, 5)

 Please Enter any String  : Tutorial Gateway

 Please Enter any Charcater that you want to search for  : G

 The Final String From G = (null)