在终端输入多行信息,找出包含“ould”的行,并打印改行。
如:
Au,love could you and I with fate conspire
To grasp this sorry scheme of things entire,
Would not we shatter it to bitd – and then.
在终端输出上述的文字,输出
Au,love could you and I with fate conspire
Au,love could you and I with fate conspire
To grasp this sorry scheme of things entire,
Would not we shatter it to bitd – and then.
Would not we shatter it to bitd – and then.
建立一个函数输入多行字符串。
建立一个函数模拟strstr函数功能判断输入的一行信息中是否包含"ould",即"ould"是不是改行字符串的子字符串。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define ROM 1000
int input(char *str,int list)
{
char ch=0;
int i=0;
while((list--)&&(ch=getchar())!=EOF&&ch!='\n')
//注意每行的限制数及有效字符,遇到结束输入
{
str[i++]=ch;
}
if(ch=='\n')
{
str[i++]='\n';//只输入一个字符'\n'时,保存'\n'
}
str[i]='\0';
return i;
}
int match(char *dest,char *src)//模拟实现strstr功能的函数
{
char *p=dest;//保存每次开始匹配的位置
assert(dest);
assert(src);
while(*p)
{
char *s1=p;
char *s2=src;//s1和s2为实际进行匹配移动到的位置
while(*s1&&*s2&&(*s1==*s2))
{
s1++;
s2++;
if(*s2=='\0')//如果s2匹配完了,就说明src是dest的子字符串
return 1;
}
p++;
}
return 0;
}
int main()
{
char str[ROM];
char arr[]="ould";
while(input(str,ROM-1))
{
if(match(str,arr))
{
printf("%s",str);
}
}
system("pause");
return 0;
}
转载于:https://blog.51cto.com/luoyafei/1711100