如何检查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;
}
答案 0 :(得分:3)
inline bool issubstr(const char *string, const char *substring )
{
return( strstr(string, substring) ) ? true: false ;
}
ststr返回指向子字符串开头的指针,如果是,则返回NULL 找不到子字符串。
更多关于strstr和朋友man page strstr
答案 1 :(得分:0)
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
答案 2 :(得分:0)
你可以使用strstr
char str1[ ] = "subtest";
char str2[ ] = "test";
int index = -1;
char * found = strstr( str1, str2);
if (found != NULL)
{
index = found - str1;
}
答案 3 :(得分: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'