C 语言中搜索字符串的程序
实施
现在,我们将看到程序的实际实施 −
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Beauty is in the eye of the beholder";
char s2[] = "the";
int n = 0;
int m = 0;
int times = 0;
int len = strlen(s2); // 包含搜索字符串的长度
while(s1[n] != '\0') {
if(s1[n] == s2[m]) { // 如果搜索字符串的第一个字符匹配
// 继续搜索
while(s1[n] == s2[m] && s1[n] !='\0') {
n++;
m++;
}
// 如果我们的字符序列与搜索字符串的长度匹配
if(m == len && (s1[n] == ' ' || s1[n] == '\0')) {
// BINGO!! we find our search string.
times++;
}
} else { // 如果搜索字符串的第一个字符不匹配
while(s1[n] != ' ') { // 跳至下一个单词
n++;
if(s1[n] == '\0')
break;
}
}
n++;
m=0; // 将计数器重置为从搜索字符串的第一个字符开始。
}
if(times > 0) {
printf("'%s' appears %d time(s)
", s2, times);
} else {
printf("'%s' does not appear in the sentence.
", s2);
}
return 0;
}
输出
此程序的输出应为 −
'the' appears 2 time(s)

string_programs_in_c.html