Check substring exists in a string in C
I'm trying to check whether a string contains a substring in C like:
char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
/* .. */
}
What is something to use instead of string::find
in C++?
if(strstr(sent, word) != NULL) {
/* ... */
}
Note that strstr
returns a pointer to the start of the word in sent
if the word word
is found.
Use strstr
for this.
http://www.cplusplus.com/reference/clibrary/cstring/strstr/
So, you'd write it like..
char *sent = "this is my sample example";
char *word = "sample";
char *pch = strstr(sent, word);
if(pch)
{
...
}
Try to use pointers...
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "String1 subString1 Strinstrnd subStr ing1subString";
char sub[] = "subString";
char *p1, *p2, *p3;
int i=0,j=0,flag=0;
p1 = str;
p2 = sub;
for(i = 0; i<strlen(str); i++)
{
if(*p1 == *p2)
{
p3 = p1;
for(j = 0;j<strlen(sub);j++)
{
if(*p3 == *p2)
{
p3++;p2++;
}
else
break;
}
p2 = sub;
if(j == strlen(sub))
{
flag = 1;
printf("\nSubstring found at index : %d\n",i);
}
}
p1++;
}
if(flag==0)
{
printf("Substring NOT found");
}
return (0);
}
You can try this one for both finding the presence of the substring and to extract and print it:
#include <stdio.h>
#include <string.h>
int main(void)
{
char mainstring[]="The quick brown fox jumps over the lazy dog";
char substring[20], *ret;
int i=0;
puts("enter the sub string to find");
fgets(substring, sizeof(substring), stdin);
substring[strlen(substring)-1]='\0';
ret=strstr(mainstring,substring);
if(strcmp((ret=strstr(mainstring,substring)),substring))
{
printf("substring is present\t");
}
printf("and the sub string is:::");
for(i=0;i<strlen(substring);i++)
{
printf("%c",*(ret+i));
}
puts("\n");
return 0;
}