输入和输出
输入:一段话,一个单词
输出:该单词是否出现在这段话中
代码
#include <stdio.h>
#include <string.h>
#define N 100
#define M 20
int isPresent(char *line, char *word);
int main(void)
{
int n, k;
char line[N], word[M];
printf("Enter a line of text:\n");
gets(line);
printf("Enter a string: ");
gets(word);
if (isPresent(line, word) == 1)
printf("\nThe string \"%s\" is present in the line.", word);
else printf("\nThe string \"%s\" is not present in the line.", word);
return 0;
}
int isPresent(char *line, char *word)
{
int i, j, status, n, m;
n = strlen(line);
m = strlen(word);
for (i = 0; i <= n - m; i++)
if (strncmp(line+i, word, m)==0) return 1;
return 0;
}
测试
总结
最开始的想法:
这个没有考虑到如果单词本身就不在这段话中的情况,本来想把这方面加进去,但是我失败了…
因为一开始就没有想着用strcpy函数,如果带着这个函数的功能一起思考,会少走很多弯路。
今天就这样,over。