2016-10-12 5 views
1

Как проверить, соответствует ли данная подстрока внутри строки в C?
Приведенный ниже код сравнивает, являются ли они равными, но если есть один внутри другого.Подтвердить подстроку в строке с помощью C

#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; 
} 
+4

Используйте [ 'strstr'] (http://en.cppreference.com/w/c/string/byte/strstr) – paddy

ответ

3

, конечно, как и @paddy указал

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

ststr возвращает указатель на начало подстроки, или NULL, если подстрока не найдена.

больше strstr и друзей man page strstr

+1

Просто добавить:' strstr 'возвращает указатель на первое вхождение в str1 всей последовательности символов, указанных в str2, или нулевой указатель, если последовательность не присутствует в str1. –

+0

хорошая опция отредактирована –

0

Вы можете использовать strstr() функцию как было упомянуто 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 
0

вы можете использовать strstr

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

if (found != NULL) 
{ 
    index = found - str1; 
} 
0

strstr Использование в <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); 

Выход:

Found the string 'is' in 'This is a test'