#include#include #include #include #include #include #define Num 20int strindex(char s[],char t[]){ int i,j,k; int position = -1; for(i = 0;s[i] != '\0';i++) { for(j = i,k = 0;t[k] != '\0' && s[j] == t[k];j++,k++) ; if(k > 0 && t[k] == '\0') position = i; } return position;}int main(){ char str1[20],str2[20]; char c; int i = 0,j = 0; int position; printf("please input string1\n"); while((c = getchar()) != '\n' && i < Num) { str1[i++] = c; } str1[i] = '\0'; printf("please input string2\n"); while((c = getchar()) != '\n' && j < Num) { str2[j++] = c; } str2[j] = '\0'; position = strindex(str1,str2); printf("%d\n",position); return 0;}
上面的程序是正确的,可以正常运行得出结果,不过,我又编了下面的函数:
#include为了不定义数组的大小就用的指针,可是程序错了。。gets函数只能读入8个字符,这里面有问题,可是我不知道哪里错了,待看完指针那章看能不能解决!#include #include #include #include #include int strindex(char s[],char t[]){ int i,j,k; int position = -1;printf("%d\n",strlen(s)); for(i = 0;i < strlen(s);i++) { printf("%d\n",i); for(j = i,k = 0;k < strlen(t) && s[j] == t[k];j++,k++) ; if(k > 0 && t[k] == '\0') position = i; } return position;}int main(){ char *str1,*str2; int i = 0,j = 0; int position; printf("please input string1\n"); gets(str1); printf("please input string2\n"); gets(str2); position = strindex(str1,str2); printf("%d\n",position); return 0;}