您的位置:首页 > 编程语言 > C语言/C++

C语言找到所有输入行中包含特定字符串的行

2011-09-27 19:54 218 查看
#include <stdio.h>
#define MAXLINE 1000 /*maximum input line length*/

int getline(char line[], int max);
int strindex(char source[], char searchfor[]);

char pattern[] = "ould"; /*pattern to search for*/
main(){
	char line[MAXLINE];
	int found = 0;

	while (getline(line, MAXLINE) > 0) {
		if (strindex(line, pattern) >= 0) {
			printf("%s", line);
			found ++;
		}
	}

	return found;

}

/*getline : get line into s, return length */
int getline(char s[], int lim){
	int c, i ;
	i = 0;
	while ( --lim > 0 && (c = getchar()) != EOF && c != '\n') {
		s[i++] = c;
	}
	if (c == '\n') {
		s[i ++] = c;
	}
	s[i] = '\0';
	return i;
}

/*strindex : return index of t in s, -1 if none*/
int strindex(char s[], char t[]){
	int i , j , k ;

	for (i = 0; s[i] != '\0'; i ++) {
		for (j = i, k = 0 ; t[k] != '\0' && s[j] == t[k]; k ++, j ++) {
			// do nothing
		}

		if (k >= 0 && t[k] == '\0') {
			return i;
		}
	}
	return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐