2016下半年計算機等級考試備考中,為方便考生複習好計算機三級網路技術,yjbys小編特整理最新網路技術模擬試題及答案解析如下:
1.編寫一個函式findStr( ),該函式統計一個長度為2的字串在另一個字串中出現的次數。例如,假定輸入的字串為"asd asasdfg asd as zx67 asd mklo",子字串為"as",函式返回值是6。
函式ReadWrite( )的功能是實現從檔案中讀取兩個字串,並呼叫函式findStr(),最後把結果輸出到檔案中。
注意:部分源程式已給出。
請勿改動主函式main() 和其他函式中的任何內容,僅在函式 findStr()的花括號中填入你所編寫的若干語句。
試題程式:
#include
#include
#include
void ReadWrite();
int findStr(char *str,char *substr)
{
}
void main()
{
char str[81],substr[3];
int n;
system("CLS");
printf("輸入原字串:");
gets(str);
printf("輸入子字串:");
gets(substr);
puts(str);
puts(substr);
n=findStr(str,substr);
printf("n=%dn",n);
ReadWrite();
}
void ReadWrite()
{
char ch,str[81],substr[3];
int n,len,i=0;
FILE *rf,*wf;
rf=fopen("","r");
wf=fopen("","w");
while(i<>
{
fgets(str,80,rf);
fgets(substr,10,rf);
len=strlen(substr)-1;
ch=substr[len];
if(ch=='n'||ch==0x1a)
substr[len]=0;
n=findStr(str,substr);
fprintf(wf,"%dn",n);
i++;
}
fclose(rf);
fclose(wf);
}【答案】
int findStr(char *str,char *substr)
{
int n=0; /*定義計數器變數,統計出現次數*/
char *p,*r; /*定義指標變數來分別指向兩個字串*/
while(*str) /*如果字串沒有結束,則一直迴圈下去*/
{
p=str; /*指標p指向字串首地址*/
r=substr; /*指標r指向子字串首地址*/
while(*r) /*若子字串沒有結束,則迴圈繼續*/
if(*r==*p)
/*如果子字串的第一個字元等於字串中的該字元,則繼續比較下一個字元*/
{
r++;
p++;
}
else
break; /*否則退出迴圈*/
if(*r=='