/*查找子串。用字符数组作函数参数,编程实现在从键盘输入的字符串(假设长度小
于 80)中查找与指定的子串,并输出该子串在字符串中首次出现的位置,如果该字符不存
在,则输出"Not found!"。*/
#include<stdio.h>
#include<string.h>
#define N 80
int SearchString(char s[], char d[]) {
int x = 1, rt = -1;
char* F[N];
int num = (int)strlen(s);
for (int xh1 = 1; xh1 < num; xh1++) {
if (s[xh1] == ' ') {
s[xh1] = '\0';
}
}//将字符串中的空格转化为字符串结束符
for (int xh2=1; xh2 < num; xh2++) {
F[0] = &s[0];
if (s[xh2] == '\0') {
F[x] = &s[xh2 + 1];
x++;
}
else continue;
}//将大字符串s分散为小字符串然后赋值给数组指针
for (int xh3 = 0; xh3 < x ; xh3++) {
if (strcmp(F[xh3], d)==0) {
rt = xh3 + 1;;
printf("运行到此处时rt=%d\n", rt);
printf("但是后面rt返回值却是初始值-1\n");
break;
}//比对各个数组指针和字符串d是否相同
else continue;
}
return rt;//返回-1表示在s中未找到字符串d
}
int main() {
char s[N], d[N];
printf("Input a string:");
gets_s(s);
printf("Input another string:");
gets_s(d);
if (SearchString(s, d)==-1) {//返回值是初始化的-1,却没执行该if语句
printf("Not found!\n");
return 0;
}
printf("Searching results:%d\n", SearchString(s, d));
}