A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_memchr.htm below:

C library - memchr() function

C library - memchr() function

The C library memchr() function of type void accepts three agruments that searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to, by the argument str.

Syntax

Following is the syntax of C library memchr() function −

void *memchr(const void *str, int c, size_t n)
Parameters

This function accepts the following parameters

Return Value

This function returns a pointer to the matching byte or NULL if the character does not occur in the given memory area.

Example 1

Following is the C library program to see the demonstration of memchr() function.

#include <stdio.h>
#include <string.h>
int main () 
{
   const char str[] = "Tutorialspoint";
   const char ch = '.';
   char *ret;
   ret = memchr(str, ch, strlen(str));
   printf("String after |%c| is - |%s|\n", ch, ret);
   return(0);
}
Output

The above code produces the following output−

String after |.| is - |.tutorialspoint.com|
Example 2

The program compares two strings using memchr() and determines whether they are equal or not.

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

int main() {
   const char str1[] = "abcdef";
   const char ch = 'd';

   char* result = (char*)memchr(str1, ch, strlen(str1));

   if (result != NULL) {
       printf("'%c' found at position %ld\n", ch, result - str1);
   } else {
       printf("'%c' not found in the string\n", ch);
   }

   return 0;
}
Output

On execution of above code, we get the following output−

'd' found at position 3
Example 3

Below the program searches for a specific character in a given string using memchr().

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

int main() {
   const char str[] = "Welcome to India";
   const char ch = 't';

   char* result = (char*)memchr(str, ch, strlen(str));

   if (result != NULL) {
       printf("'%c' found at position %ld\n", ch, result - str);
   } else {
       printf("'%c' not found in the string\n", ch);
   }
   
   return 0;
}
Output

After executing the above code, we get the following output−

't' found at position 8

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4