strstr(): searching for matching string

We can search and get the pointer of first occurance of mathching string by using strstr() string function.
strstr(main_string, search_string);
Output is pointer of first occurrence of matching string. Returns null if searched string is not found.
#include <stdio.h>
#include <string.h>
int main(void){
   char str[100]="Welcome to C section of plus2net";
   char str_search[20]="to C";
   char *p;
   p = strstr(str,str_search);
   printf("Position :%d",p-str+1);
   return 0;
}
The output of above code is here
Position :9
In above code, by subtracting the pointer of main string and by adding 1 to it , we will get the position of matching string related to main string.

As we get a pointer by using strstr() , so we can display the string value so rest of the string starting from searched string will be returned.
#include <stdio.h>
#include <string.h>
int main(void){
   char str[100]="Welcome to plus2net";
   char *p;
   p = strstr(str,'m');
   printf("Position :%d , %s",p-str+1,p);
   return 0;
}
Output is here
Position :9, to C section of plus2net

Example of string search and replacement using strstr()

#include <stdio.h>
#include <string.h>
int main(void){
   char str[100]="Welcome to C section of plus2net";
   char str_search[20]="to C";
   char *p;
   p = strstr(str,str_search);
   if(p){
    strcpy(p, "to PHP section of plus2net");
    printf("%s",str);
   }else{
   printf(" No matching found ");
   }
   return 0;
}
Welcome to PHP section of plus2net

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer