北航计算机机试09字符串的查找删除

来源:互联网 发布:seo怎么自学 编辑:程序博客网 时间:2024/05/16 15:56

字符串的查找删除
给定文件filein.txt 按要求输出fileout.txt。
输入:无空格的字符串
输出:将filein.txt删除输入的字符串(不区分大小写),输出至fileout.txt
sample
输入:in
输出:将filein.txt 中的In、IN、iN、in删除,每行中的空格全部提前至行首,输出至fileout.txt
filein.txt中的值为:

#include <stdio.h>int main(){printf(" Hi ");}输出的fileout.txt为#clude<stdio.h>tma(){prtf("Hi");}

代码:

#include<stdio.h>#include<string.h>#include<ctype.h>int main(){    FILE *fp_in,*fp_out;    char a[100],b[100];    while(scanf("%s",a)!=EOF)    {        int len=strlen(a);        fp_in=fopen("filein.txt","r");        fp_out=fopen("fileout.txt","w");        char ch;        int i=0;        int j=0;        while((ch=fgetc(fp_in))!=EOF)        {            int flag=0;            if(tolower(ch)==tolower(a[0]))             {                for(i=1;i<len&&flag==0;i++)                {                char get=fgetc(fp_in);                b[i-1]=get;                if(tolower(get)!=tolower(a[i]))                 {   flag=1;                    fputc(ch,fp_out);                    for(int j=0;j<i;j++)                    {                        if(b[j]!=' ')                         {                            fputc(b[j],fp_out);                        }                    }                }                }            }            else{            if(ch!=' ') fputc(ch,fp_out);               }        }    fclose(fp_in);    fclose(fp_out);    }    return 0;}

思路
北航的题目我一直读不懂
这个题目的意思好像是从文件读出,写到文件中,又好像是存到一维数组中,所以我就按照文件输入的方法来写了

从filein.txt文件中读入字符,每个字符都存到字符ch中,每读入一个就进行判断,若有匹配,则略过不输出,否则将不匹配的非空格都输出。

文件输入:
使用文件前必须打开文件,用fopen()函数来打开文件
FILE* fopen(const char * filename,const char *mode)
r只读,w只写(覆盖)
flose()用来关闭一个由函数fopen打开的文件
关闭成功返回0,否则返回非0值

按字符读写文件‘

fgetc()用于从一个以只读或读写方式打开的文件上读字符
fputc()用于将一个字符写到一个文件上

FILE *fp;char ch;if((fp=fopen("dome.txt","w"))==NULL){printf("Failure to open file");exit(0);}ch=getchar();while(ch!='\n'){fputc(ch,fp);ch=getchar();}fclose(fp);

///使用getchar输入字符时,并非每键入一个字符就赋值给ch,而是先将所有字符送入缓冲区,直到键入回车键才从缓冲区中逐个读出并赋值给ch

while((ch=fgetc(fp))!=EOF){putchar(ch);}

文件末尾为EOF

读写文件中的字符串

fgets(char *s,int n,FILE *fp)函数用来从文件中读取字符串
从fp中读取字符并在字符串末尾添加’\0’,然后存入s,最多存入n-1个字符。当读到回车换行符,文件末尾或读满之后,函数返回该字符串的首地址
fputs()用来将字符串写入文件

FILE *fp;char str[N];gets(str);fputs(str,fp);fgets(str,N,fp);
0 0
原创粉丝点击