You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何判断一个字符串是否包含另一个较短子串

C语言实现子串查找的解决方法

你已经引入了<string.h>头文件,直接调用标准库提供的strstr函数即可实现子串查找功能,该函数的原型为:
char *strstr(const char *haystack, const char *needle)

  • 第一个参数是要被搜索的长字符串
  • 第二个参数是要查找的短子串
  • 若找到子串,返回子串在长字符串中第一次出现的起始地址;没找到返回NULL指针

另外现有代码存在一个隐患:输入长度为size1的字符串时,字符串末尾的结束符\0没有额外存储空间,会触发数组越界,建议调整数组申请长度为输入大小+1。

修改后完整代码

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
    
int main()
{
    printf("Please enter string 1 size and then enter a text: ");
    int size1;
    scanf("%d", &size1);
    char test1[size1 + 1]; // 多留1位存储字符串结束符
    scanf("%s", test1);
   
    printf("Please enter string 2 size and then enter a text: ");
    int size2;
    scanf("%d", &size2);
    char test2[size2 + 1]; // 多留1位存储字符串结束符
    scanf("%s", test2);
    
    int test1_len = strlen(test1);
    int test2_len = strlen(test2);
    char *match_pos = NULL;
    
    if (test1_len < test2_len)
    {
        match_pos = strstr(test2, test1);
        if (match_pos != NULL) {
            printf("较短的字符串\"%s\"存在于较长的字符串\"%s\"中,首次出现的起始偏移为%ld\n", test1, test2, match_pos - test2);
        } else {
            printf("较短的字符串\"%s\"不存在于较长的字符串\"%s\"中\n", test1, test2);
        }
    }
    else
    {
        match_pos = strstr(test1, test2);
        if (match_pos != NULL) {
            printf("较短的字符串\"%s\"存在于较长的字符串\"%s\"中,首次出现的起始偏移为%ld\n", test2, test1, match_pos - test1);
        } else {
            printf("较短的字符串\"%s\"不存在于较长的字符串\"%s\"中\n", test2, test1);
        }
    }
    
    return 0;
}

如果不想调用库函数要手动实现子串查找逻辑,可以用双层循环实现:外层遍历长字符串的每个字符作为匹配起始位置,内层逐个比对短字符串的每个字符,全部匹配成功则说明存在子串。

内容的提问来源于stack exchange,提问作者Hadi Jafari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:57:00