C语言笔记

查找子串(4分)
题目内容:

用字符数组作函数参数,编程实现在从键盘输入的字符串(假设长度小于80)中查找与指定的子串,并输出该子串在字符串中首次出现的位置,如果该字符不存在,则输出"Not found!"。

函数原型:int SearchString(char s[], char d[])

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

程序运行结果示例1:

Input a string:How are you!↙

Input another string:are↙

Searching results:5

程序运行结果示例2:

Input a string:hello↙

Input another string:are↙

Not found!

程序运行结果示例3:

Input a string:You are a student.↙

Input another string:you↙

Not found!

输入第一个字符串的提示信息:“Input a string:”

输入第二个字符串的提示信息:“Input another string:”

输入格式: gets()

输出格式:“Searching results:%d\n”

没找到子串的输出提示信息: “Not found!\n”

注意:为避免出现格式错误,请直接拷贝粘贴上面给出的输入、输出提示信息和格式控制字符串!

#include <stdio.h>
#include <stdlib.h>
#define Max 80
int SearchString(char s[], char d[]);
int main()
{   int i;
    char s[Max];
    char d[Max];
    printf("Input a string:");
    gets(s);
    printf("Input another string:");
    gets(d);
    if(SearchString(s,d)==-1)
        printf("Not found!\n");
    else
        printf("Searching results:%d\n",SearchString(s,d));
    return 0;
}
int SearchString(char s[], char d[])
{
    int i=0,j=0;
    while(s[i]!='\0'&& d[j]!='\0')
    {
       if(s[i]==d[j])
        i++,j++;
    else
    {i=i-j+1,j=0;} }
    if(d[j]=='\0')
    return i-j+1;
    else
        return -1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值