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);
}

原文链接: https://www.cnblogs.com/tian0926/p/14887055.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/211393

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午12:47
下一篇 2023年2月13日 上午12:48

相关推荐