C语言:输入两个字符串,在字符串1中查找字符串2,并返回字符串2在字符串1中第一次出现的位置。

输入两个字符串,在字符串1中查找字符串2,并返回字符串2在字符串1中第一次出现的位置。


#include<stdio.h>
#include<string.h>
#define SIZE 50
void s_gets(char *s1,int index);    //读取字符串,将换行符去掉
void location(char *s1,char *s2);    //寻找s1在s2中的位置
int main(void)
{
    char mainstring[SIZE];
    char str2[SIZE];
    s_gets(mainstring,SIZE);
    s_gets(str2,SIZE);
    location(mainstring,str2);
    return 0;
}
void s_gets(char *s1,int index)
{
    char * exceptional_case;
    exceptional_case=fgets(s1,index,stdin);
    while(*s1++)
        if(*s1=='\n')
            *s1='\0';
}
void location(char *s1,char *s2)
{
    char *p;
    int n=0;
    int nofound=-1;
    while(p=strstr(s1+n,s2))
    {
        n=p-s1;
        printf("%d ",n++);
        if(nofound)
            nofound=0;
    }
    if(nofound)
        printf("%d",nofound);
}