一、实现功能:
若输入字符串: What would you recommend to others?
I am a student.
Somewould like that to change.
寻找目标字符串:oul,若含有目标字符串,则将其进行拷贝输出
二、代码:
#include <stdio.h>
#include <assert.h>
#include <string.h>
#define MAX 1000 //输入字符串长度
//输入字符串函数
int getline(char line[], int max)
{
int ch;
int i = 0;
while (max > 0 &&
(ch = getchar()) != EOF && ch != '\n')
{
line[i] = ch;
i++;
max--;
}
if (ch == '\n')
line[i++] = '\n';
line[i] = '\0';
if (i > 0)
return 1;
else
return 0;
}
//匹配字符串
int match(char line[], char *mat)
{
assert(line); //断言
assert(mat);
int i = 0, j = 0, k = 0;
for (i = 0; i < strlen(line); i++)
{
for (k = i, j = 0; j < strlen(mat); j++, k++)
{
if (line[k] != *(mat + j))
break;
}
if (*(mat + j) == '\0' && k>0)
return 1;
}
return 0;
}
int main()
{
char line[MAX];
char *mat = "oul";
while (getline(line, MAX))
{
if (match(line, mat))
printf("%s", line);
}
return 0;
}
注意:在匹配时,要考虑到字符串中含有
oooul的情况
三、运行结果:
Some would like that to change