指標作為函式引數,指標訪問字元陣列元素06(C)
阿新 • • 發佈:2019-02-06
編寫一個函式,查詢字串s1 中是否包含字串 s2,並返回找到的第一個子串的起始位置,如果 s1 中沒有 s2, 則返回-1。編寫程式測試該函式。例如: s1: abcdefghdef, s2: def。則函式返回第一個 def 的起始位置: 3。
/*================================================================================================================ *學號:1527403059 *作業:E70 *功能:查詢字串s1中是否包含字串s2,並返回找到的第一個子串的起始位置,如果s1中沒有s2則返回-1。編寫程式測試該函式 *作者:陸胤任 *日期:2015.12.26 *===================================================================================================================*/ #include<stdio.h> #define N 100 /*function define *@brief:查詢字串s1中是否包含字串s2,並返回找到的第一個子串的起始位置,如果s1中沒有s2,則返回-1 *@param:char *p1:首地址 char *p2:首地址 int flag:字串的起始位置 *@reval:flag:字串的起始地址 -1:沒有子字串*/ int find_str1_str2(char *p1,char *p2) //定義find_str1_str2(char *p1,char *p2)函式 { int count1=0,count2=0; int count; int i,j,k,a; int flag; while(p1[count1]!='\0') //計算s1的實際長度 { count1++; } while(p2[count2]!='\0') //計算s2的實際長度 { count2++; } for(i=0;i<count1;i++) //迴圈判斷s1中是否有子字串s2 { if(p1[i]==p2[0]) { a=i; //儲存子字串首地址 count=0; for(k=i,j=0;k<=i+count2-1,j<=count2-1;k++,j++) { if(p1[k]==p2[j]) { count++; } else { //若沒有子字串則讓a=-1 count=0; } } } } if(count==count2) { flag=a; } else { flag=-1; } return flag; //把變數flag的值作為函式返回值 } /*test program*/ int main() { char str1[100],str2[100]; int flag; printf("請輸入長度小於100的字串str1:\n"); gets(str1); //輸入字串str1 printf("請輸入長度小於100的字串str2:\n"); gets(str2); //輸入字串str2 flag=find_str1_str2(str1,str2); //呼叫find_str1_str2(char *p1,char *p2)函式 if(flag==-1) { printf("字串str1中不包含子字串str2\n"); } else { printf("字串str1中包含子字串str2,字串首地址為%d\n",flag); } return 0; }