-->





string class function memchr c example

In string class memchr() function helps us to find a byte within a specific memory block. It takes three parameters memchr(buffer, char, size); and returns pointer to first occurrence where char is found else it returns NULL.



Buffer: Memory block in which a byte to be searched
char: Character to search in buffer
size: Size of buffer.

C++ source code: Compiler used CodeBlocks

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main ()
{
    char buffer[] = "I like c++ programming";
    cout<<"We have this string -> \n";
    puts(buffer);
    char key;
    char *result;
    cout<<"Enter a character to search in string:  ";
    cin>>key;
    cout<<endl;

    result = (char*)memchr(buffer, key, strlen(buffer));

    if (result!=NULL)
        cout<<key<<" is found at index number:  "<<(result-buffer) ;
     else
        cout<<" NOT FOUND";
    
    cout<<endl;
 return 0;
}


Input output code


program output
string class function memchr c++ example





0 comments:

Post a Comment