1

How to check if a given substring within a string in C?
The code below compares whether they are equal, but if there is one inside the other.

#include <stdio.h>
#include <string.h>
int main( )
{
   char str1[ ] = "test" ;
   char str2[ ] = "subtest" ;
   int i, j, k ;
   i = strcmp ( str1, "test" ) ;
   j = strcmp ( str1, str2 ) ;
   k = strcmp ( str1, "t" ) ;
   printf ( "\n%d %d %d", i, j, k ) ;
   return 0;
}
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
deepCode
  • 21
  • 3

4 Answers4

3

surely, as @paddy pointed

inline bool issubstr(const char *string, const char *substring )
{
    return( strstr(string, substring) ) ?  true: false ;
}

ststr return a pointer to the beginning of the substring, or NULL if the substring is not found.

more on strstr and friends man page strstr

asio_guy
  • 3,667
  • 2
  • 19
  • 35
0

You can use strstr() function as mentioned by paddy

 strstr() function returns the first occurance of the substring in a string.  If you are to find all occurances of a substring in a string than you have to use "String matching " algorithms such as,    
1)Naive String Matching
2)Rabin Karp   
3)Knuth Morris Pratt
Prashant Anuragi
  • 390
  • 4
  • 14
0

you can use strstr

char str1[ ] = "subtest";
char str2[ ] = "test";
int index = -1;
char * found = strstr( str1, str2);

if (found != NULL)
{
  index = found - str1;
}
Russell Jonakin
  • 1,716
  • 17
  • 18
0

Using strstr in <string.h>

char* str = "This is a test";
char* sub = "is";
char* pos = strstr(str, sub);
if (pos != NULL)
    printf("Found the string '%s' in '%s'\n", sub, str);

Output:

Found the string 'is' in 'This is a test'
Andreas DM
  • 10,685
  • 6
  • 35
  • 62