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

如何修改C语言代码以定位子字符串在母串中的出现位置

修改代码以获取子字符串在母串中的起始位置

你现有的代码通过递归实现了子串存在性检查,要获取具体位置,核心是在遍历母串时跟踪当前的索引,并在匹配成功时返回该索引,未找到则返回-1(通常用-1表示不存在)。

修改思路

  1. 放弃仅返回布尔值的设计,改为返回整数:匹配成功返回起始下标,失败返回-1
  2. 遍历母串时记录当前位置,当发现首字符匹配时,检查后续字符是否完全匹配
  3. 保留原递归匹配逻辑,仅调整外层遍历函数的返回值逻辑

完整修改后的代码

#include <stdio.h>
#include <stdbool.h>

// 从当前strng位置开始,检查是否完全匹配subs,匹配返回true,否则false
bool checksub(const char *strng, const char *subs) {
    if (*strng == '\0' && *subs != '\0') {
        return false;
    }
    if (*subs == '\0') {
        return true;
    }
    if (*strng == *subs) {
        return checksub(strng + 1, subs + 1);
    }
    return false;
}

// 遍历母串,返回子串的起始索引,未找到返回-1
int find_sub_index(const char *strng, const char *subs) {
    // 处理空串情况:空串默认在0位置
    if (*subs == '\0') {
        return 0;
    }
    // 遍历母串,同时记录当前索引
    int index = 0;
    while (*strng != '\0') {
        if (*strng == *subs) {
            // 检查从当前位置开始是否完全匹配子串
            if (checksub(strng, subs)) {
                return index;
            }
        }
        strng++;
        index++;
    }
    // 遍历完没找到,返回-1
    return -1;
}

int main() {
    int idx1 = find_sub_index("ababuu", "ab");
    printf("子串\"ab\"的起始位置:%d\n", idx1);
    
    int idx2 = find_sub_index("the bed bug bites", "bit");
    printf("子串\"bit\"的起始位置:%d\n", idx2);
    
    int idx3 = find_sub_index("hello world", "xyz");
    printf("子串\"xyz\"的起始位置:%d\n", idx3);
    return 0;
}

代码说明

  • checksub函数保留原有的递归匹配逻辑,仅用于判断从当前位置开始是否能完全匹配子串
  • find_sub_index函数改为返回索引:遍历母串时记录index,每移动一个字符索引加1;当首字符匹配时调用checksub,成功则返回当前索引
  • 增加了空串和未找到的边界处理:空串返回0,未找到返回-1

运行结果

子串"ab"的起始位置:0
子串"bit"的起始位置:12
子串"xyz"的起始位置:-1

如果想要支持查找所有匹配位置,可以修改为直接打印所有匹配索引,比如:

// 查找所有匹配的起始位置并打印
void find_all_sub_indices(const char *strng, const char *subs) {
    if (*subs == '\0') {
        printf("空串匹配所有位置\n");
        return;
    }
    int index = 0;
    printf("所有匹配位置:");
    while (*strng != '\0') {
        if (*strng == *subs && checksub(strng, subs)) {
            printf("%d ", index);
        }
        strng++;
        index++;
    }
    printf("\n");
}

// 在main中调用示例:
find_all_sub_indices("ababuu", "ab"); // 输出:所有匹配位置:0 2 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:30:41