实验11-1-8 查找子串

本题要求实现一个字符串查找的简单函数。

函数接口定义:

c 复制代码
char *search( char *s, char *t );

函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。
输入样例1:

c 复制代码
The C Programming Language
ram

输出样例1:

c 复制代码
10

输入样例2:

c 复制代码
The C Programming Language
bored

输出样例2:

c 复制代码
-1

具体程序:

c 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#define MAXS 30

char* search(char* s, char* t);

int main()
{
    char s[MAXS], t[MAXS], * pos;

    gets(s);
    gets(t);
    pos = search(s, t);
    if (pos != NULL)
        printf("%d\n", pos - s);
    else
        printf("-1\n");

    return 0;
}
char* search(char* s, char* t)
{
    int i = 0;
    while (*(s + i) != '\0')
    {
        if (*(s + i) == *t)
        {
            int j = 0;
            while (*(t + j) != '\0')
            {
                if (*(s + i + j) != *(t + j))break;
                j++;
            }
            if (*(t + j) == '\0')
                return(s + i);
        }
        i++;
    }
    return NULL;
}

运行效果:

相关推荐
大可不必了10 小时前
03 函数定义和调用
开发语言·python
I_belong_to_jesus10 小时前
C++关于分支预测的优化1
开发语言·c++·算法
承渊政道11 小时前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛11 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
eggwyw13 小时前
Anaconda安装卸载的详细流程指南
开发语言·python
another heaven17 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude17 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
上海潭龙东海科技有限公司18 小时前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
SomeOtherTime19 小时前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust