C语言:判断输入一行中是否包含模式串

C语言:函数与程序结构1


1
#include<stdio.h> 2 #define MAXLINE 1000 /*最大输入行长度 */ 3 4 int getline(char line[], int max); 5 int strindex(char source[], char searchfor[]); 6 7 char pattern[] = "ould"; /*待查的模式*/ 8 9 /*找出所以与模式匹配的行*/ 10 main() 11 { 12 char line[MAXLINE]; 13 int found = 0; 14 15 while(getline(line,MAXLINE)>0) 16 { 17 if(strindex(line,pattern)>=0) 18 { 19 printf("%s",line); 20 found++; 21 } 22 } 23 return found; 24 } 25 26 /*getline函数,将行保存到s中,并返回改行的长度*/ 27 int getline(char s[], int lim) 28 { 29 int c,i; 30 i = 0; 31 while(--lim>0 && (c=getchar())!=EOF && c!='\n') 32 { 33 s[i++] = c; 34 } 35 if(c=='\n') 36 { 37 s[i++] = c; 38 } 39 s[i] = '\0'; 40 return i; 41 } 42 43 /*strindex函数,返回t在s中的位置,若未找到则返回-1*/ 44 int strindex(char s[], char t[]) 45 { 46 int i,j,k; 47 48 for(i=0;s[i]!='\0';i++) 49 { 50 for(j=i,k=0;t[k]!='\0'&&s[j]==t[k];j++,k++) 51 ; 52 if(k>0 && t[k]=='\0') 53 return i; 54 } 55 return -1; 56 }

猜你喜欢

转载自www.cnblogs.com/kyrie211/p/10060889.html