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;
}
1
  • 4
    Use strstr Commented Oct 12, 2016 at 2:53

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Just to add : strstr returns a pointer to the first occurrence in str1 of the entire sequence of characters specified in str2, or a null pointer if the sequence is not present in str1.
good option edited
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;
}

Comments

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

Comments

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.