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.
#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
#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
Check if a specific word exists in the string using strstr() and print an appropriate message.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "C programming is fun";
char *word = "fun";
if (strstr(str, word)) {
printf("The word '%s' was found in the string.\n", word);
} else {
printf("The word '%s' was not found in the string.\n", word);
}
return 0;
}
Output:
The word 'fun' was found in the string.
---
This example allows users to input a string and a substring, then checks if the substring is present.
#include <stdio.h>
#include <string.h>
int main() {
char str[100], substr[50];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline
printf("Enter a substring to search for: ");
fgets(substr, sizeof(substr), stdin);
substr[strcspn(substr, "\n")] = '\0'; // Remove newline
if (strstr(str, substr)) {
printf("The substring '%s' was found in the string.\n", substr);
} else {
printf("The substring '%s' was not found in the string.\n", substr);
}
return 0;
}
Output:
Enter a string: Welcome to the world of programming
Enter a substring to search for: programming
The substring 'programming' was found in the string.