一、實現功能:
若輸入字符串: 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的情況
三、運行結果: