C语言字符串:查找子串首次出现的位置(下标)

输入字符串str、sub,查找sub在str首次出现的位置(下标)。例如str= " 123aba3abc", sub= “3ab ",sub在str中首次出现的下标为2,sub、 str长度 不超过50。

输入格式:

输入包括两行,依次是字符串str, sub.

输出格式:

sub在str中首次出现的位置(下标)。如果sub不在str中输出"NO"。

//方法一

#include<stdio.h>
#include<string.h>
int main(){
char a[100],b[100];gets(a);gets(b);
int c=0,t,i,f=0;
char *p=a,*q=b,*v=a;
for(;*p;p++){
if(*p==*b){
v=p;
for(q=b;*q;q++){
if(*p++==*q)c++;
}
if(c==strlen(b)){
f=1;printf("%d",v-a);break;
}
else p=p-c+1;
c=0;
}
}
if(f==0)printf("NO");
return 0;
}

//方法二(不完整)

#include <stdio.h>
#include <string.h>
int main()
{
char str[50],stu[50],*p=str,*q=stu;
int x=0,f=1,y=0;
scanf("%s",str);
scanf("%s",stu);
while (*p) {
f=1;
q=stu;
y=0;
if (*p==*q) {
while (*q) {
if (*p!=*q ) {
f=0;
break;
}
p++;q++;y++;
}
if (f==0) {
x+=1;
p=p-y+1;
continue;
}
if (f==1) break;
}
p++;x++;
}
printf("%d",x);
}

posted @ 2021-06-15 20:39  不浪费时光  阅读(3696)  评论(0编辑  收藏  举报