memchr() in C++

memchr(): This function is available in the file string.h. This function searches within the first num bytes of the block of memory pointed by ptr for the first occurrence of value (interpreted as an unsigned char) and return a pointer to it.

Syntax:

void *memchr(const void *ptr, int value, size_t num)

Parameters: Three parameters are required for this function.

ptr: Pointer to the block of memory where the search is performed.

value: Value to be located. The value is passed as an int, but the function performs a byte per byte search using the unsigned char conversion of this value. 

num: Number of bytes to be analyzed. size_t is an unsigned integral type.

For Example:

str = "Hello World"

memchr(str,'l',sizeof(str)) = >  It points to first l in the string.

Note: 

1.If the value is found it returns a pointer to the first occurrence of a value in the block of memory pointed by ptr.

2.If the value is not found, the function returns a null pointer.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    char str[] = "Hello World";
    char ch = 'l';
    char *pt = (char *)memchr(strchsizeof(str));

    if (pt != NULL)
        cout << ch << " found at position " << pt - str << "\n";
    else
        cout << ch << " not found in the string\n";

    return 0;
}


Output: l found at position 2

No comments:

Post a Comment