在终端输入多行信息,找出包含“ould”的行(也可以自定义其他的查找信息),并打印该行。
#include<stdio.h>
#include<assert.h>
#define LINE_MAX 1000
char *fine_sub_str(char *line, char *substr)//在不允许调用库函数的情况下自己写出相当于strstr的函数。
{
char *str1 = line;
char *str2 = substr;
char *start = NULL;
assert(line);
assert(substr);
if (*str2 == '\0')
{
return str1;
}
while (*str1)
{
start = str1;
while ((*str1) && (*str2) && (*str1 == *str2))
{
str1++;
str2++;
}
if (*str2 == '\0')
{
return start;
}
str2 = substr;
str1 = start + 1;
}
return NULL;
}
int getline(char line[], int limit)//执行输入字符串并保存的操作并且返回值用作while循环的条件
{
int ch = 0;
int i = 0;
while ((--limit) && (ch = getchar()) && (ch != '\n') && (ch != EOF))
{
line[i++] = ch;
}
if (ch == '\n')
{
line[i++] = '\n';
}
line[i] = '\0';
return i;
}
int main()
{
char line[LINE_MAX];
while (getline(line, LINE_MAX))
{
if (fine_sub_str(line, "ould"))
{
printf("%s", line);
}
}
system("pause");
return 0;
}
#include<stdio.h>
#include<assert.h>
#define LINE_MAX 1000
char *fine_sub_str(char *line, char *substr)//在不允许调用库函数的情况下自己写出相当于strstr的函数。
{
char *str1 = line;
char *str2 = substr;
char *start = NULL;
assert(line);
assert(substr);
if (*str2 == '\0')
{
return str1;
}
while (*str1)
{
start = str1;
while ((*str1) && (*str2) && (*str1 == *str2))
{
str1++;
str2++;
}
if (*str2 == '\0')
{
return start;
}
str2 = substr;
str1 = start + 1;
}
return NULL;
}
int getline(char line[], int limit)//执行输入字符串并保存的操作并且返回值用作while循环的条件
{
int ch = 0;
int i = 0;
while ((--limit) && (ch = getchar()) && (ch != '\n') && (ch != EOF))
{
line[i++] = ch;
}
if (ch == '\n')
{
line[i++] = '\n';
}
line[i] = '\0';
return i;
}
int main()
{
char line[LINE_MAX];
while (getline(line, LINE_MAX))
{
if (fine_sub_str(line, "ould"))
{
printf("%s", line);
}
}
system("pause");
return 0;
}