6-4 查找子串

By | 最新修改:2024-08-17

这是 拼题A(PTA)《中M2019秋C入门和进阶练习集》的习题。原题在 https://pintia.cn/problem-sets/1163286449659043840/problems/1174288506294865923 (侵删)
本人的答案仅供交流学习,请勿用于当作答案来提交!

题目描述:

6-4 查找子串 (20 point(s))
本题要求实现一个字符串查找的简单函数。

函数接口定义:

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

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

裁判测试程序样例:

#include <stdio.h>
#define MAXS 30

char *search(char *s, char *t);
void ReadString( char s[] ); // 裁判提供,细节不表

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

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

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例1:
The C Programming Language
ram
输出样例1:
10
输入样例2:
The C Programming Language
bored
输出样例2:
-1

我的答案:

/*================================================================
*   Copyright (C) 2019 程序知路. All rights reserved.
*   
*   Filename    :6-4-查找子串.c
*   Author      :程序知路
*   E-Mail      :admin@icxzl.com
*   Create Date :2019年09月25日
*   Description :
================================================================*/
#include <stdio.h>
#define MAXS 30

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

int main()
{
    char s[MAXS] = "The C Programming Language";
    char t[MAXS] = "uage"; 
    char *pos;

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

    return 0;
}

// 以下才是有效代码,这才是答案:
char *search(char *s, char *t) {

    char* ps;
    char* pt;
    while (*s != '\0') {
        if (*t == '\0')
            return NULL;

        if (*s == *t) {
            ps = s;
            pt = t;
            while (*(++s) != '\0' && *(++t) != '\0' && *s == *t)
                ;

            if (*s == '\0') {
                if (*(++t) == '\0') {
                    return ps;
                } else 
                    return NULL;
            } else if (*t == '\0') {
                return ps;
            } else {
                t = pt;
            }
        }
        s ++;
    }

    return NULL;
}

程序知路

鉴于本人的相关知识储备以及能力有限,本博客的观点和描述如有错漏或是有考虑不周到的地方还请多多包涵,欢迎互相探讨,一起学习,共同进步。

本文章可以转载,但是需要说明来源出处!

本文使用的部分图片来源于网上,若是侵权,请与本文作者联系删除: admin@icxzl.com