C語言的範例 –計算字串中子串出現的次數
題目:計算字串中子串出現的次數
1.程式分析:
2.程式源代碼:
#include "string.h"
#include "stdio.h"
main()
{ char str1[20],str2[20],*p1,*p2;
int sum=0;
printf("please input two strings\n");
scanf("%s%s",str1,str2);
p1=str1;p2=str2;
while(*p1!='\0')
{
if(*p1==*p2)
{while(*p1==*p2&&*p2!='\0')
{p1++;
p2++;}
}
else
p1++;
if(*p2=='\0')
sum++;
p2=str2;
}
printf("%d",sum);
getch();}
==============================================================
C語言的範例 –資料存取
題目:從鍵盤輸入一些字元,逐個把它們送到磁片上去,直到輸入一個#為止。
1.程式分析:
2.程式源代碼:
#include "stdio.h"
main()
{ FILE *fp;
char ch,filename[10];
scanf("%s",filename);
if((fp=fopen(filename,"w"))==NULL)
{printf("cannot open file\n");
exit(0);}
ch=getchar();
ch=getchar();
while(ch!='#')
{fputc(ch,fp);putchar(ch);
ch=getchar();
}
fclose(fp);
}