c语言编程显示按键字符,C语言编程:从键盘输入一个字符串,查找指定子串第一次出现的位置。求问题补充里的程序...

C语言编程:从键盘输入一个字符串,查找指定子串第一次出现的位置。求问题补充里的程序

关注:94  答案:3  手机版

解决时间 2021-03-05 23:16

提问者一段小時光

2021-03-05 00:46

例:输入abcccde,指定子串为cd,则输出为5

最佳答案

二级知识专家有你才幸福

2021-03-05 02:14

原理类似于找素数,以下是具体代码(附注释):

#include 

#include 

#include 

int SearchString(char s[], char d[]);

main()

{

char s[81];  //储存一串字符

char d[10];  //储存要查找的字符

int flag;

//输入一串字符

printf("Input a string:");

gets(s);

//输入想要查找的字符

printf("Input another string:");

gets(d);

//调用函数,输出结果

flag=SearchString(s,d);

if(flag==-1)

printf("Not found!\n");

else

printf("Searching results:%d\n",flag);

system("pause");

}

//函数功能:在字符数组s中查找子串d,返回d在s中首次出现的位置,若找不到,则返回-1

int SearchString(char s[], char d[])

{

int location=-1;

int i,j;

//第一层循环遍历被查找字符串

for(i=0;s[i]!='\0';i++)

{

//第二层循环遍历要查找的字符,若有不同的字符则退出该循环

for(j=0;d[j]!='\0';j++)

{

if(s[i+j]!=d[j])

break;

}

//判断第二层循环是否全部执行,若全部执行则表示字符相等,保存位置

if(d[j]=='\0')

{

location=i+1;

break;

}

}

return location;

}

全部回答

1楼守給你的承諾

2021-03-05 03:56

#include

#include

char buf[1024],search[128];

int main(){

printf("Read String:");scanf("%s",buf);

printf("Read Substr:");scanf("%s",search);

char * pos = strstr(buf,search);

if (pos==NULL)

printf("Can't found \"%s\"\n",search);

else

printf("%d\n",pos-buf+1);

return 0;

}利用string.h库函数strstr()查找子串

2楼甜心萌物酱

2021-03-05 03:29

#include

int main()

{

int i,j;

char s1[100],s2[100];

scanf("%s%s",s1,s2);

for(i=0;i<100;i++)

{

if(s1[i]=='\0' ) break;

for(j=0;j<100;j++)

if(s2[j]=='\0' || s2[j]!=s1[j+i]) break;

if(s2[j]=='\0' ) {printf("位置是:%d",i+1); break;}

}

if(s1[i]=='\0' ) printf("没找到");

}

我要举报

如以上信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!

推荐资讯

大家都在看

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值