实验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;
}

运行效果:

相关推荐
这不小天嘛5 小时前
JAVA八股——J集合篇
java·开发语言
AOwhisky6 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
ysu_03146 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
ysu_03146 小时前
06 | 200个单元测试C项目也能TDD
c语言·单元测试·tdd
浮沉9877 小时前
二分查找算法概述&通用模板
算法
Keven_118 小时前
算法札记:SPFA判负环算法的证明
算法
什巳8 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
喜欢的名字被抢了8 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi