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

在C语言中用strchr处理多/字符,获取指定位置子串并存储的方法

解决你的两个字符串提取需求

嘿,我来帮你搞定这两个字符串提取的需求,咱们直接结合思路和代码来讲解:

需求1:获取第二个'/'之后的子串“local”

核心思路是先定位第一个/,再从它的下一位开始找第二个/,然后提取两个/之间的内容:

#include <stdio.h>
#include <string.h>

int main() {
    char buf[50] = "user/local/etc/bin/example.txt";
    char* first_slash = strchr(buf, '/');
    if (first_slash == NULL) {
        printf("未找到斜杠\n");
        return 1;
    }
    // 从第一个斜杠的下一位开始,定位第二个斜杠
    char* second_slash = strchr(first_slash + 1, '/');
    if (second_slash == NULL) {
        printf("未找到第二个斜杠\n");
        return 1;
    }
    char local[20];
    // 提取第一个斜杠后到第二个斜杠前的内容
    strncpy(local, first_slash + 1, second_slash - (first_slash + 1));
    local[second_slash - (first_slash + 1)] = '\0'; // 手动添加字符串终止符
    printf("第二个/之后的子串:%s\n", local); // 输出 local
    return 0;
}

需求2:获取最后一个'/'之后不带.txt后缀的子串“example”

这里用到strrchr(找字符串最后出现的目标字符),先定位最后一个/,再找文件名里的最后一个.,提取中间的内容:

#include <stdio.h>
#include <string.h>

int main() {
    char buf[50] = "user/local/etc/bin/example.txt";
    // 定位最后一个斜杠的位置
    char* last_slash = strrchr(buf, '/');
    if (last_slash == NULL) {
        printf("未找到斜杠\n");
        return 1;
    }
    char* filename_start = last_slash + 1; // 文件名的起始位置
    // 定位文件名里最后一个点的位置
    char* dot = strrchr(filename_start, '.');
    char example[20];
    if (dot != NULL) {
        // 提取文件名开头到点之前的内容
        strncpy(example, filename_start, dot - filename_start);
        example[dot - filename_start] = '\0';
    } else {
        // 如果没有后缀,直接复制整个文件名
        strcpy(example, filename_start);
    }
    printf("最后一个/之后不带后缀的子串:%s\n", example); // 输出 example
    return 0;
}

你也可以把两个需求整合到同一个程序里,上面分开写是为了让逻辑更清晰。另外加上空指针检查,能避免程序在异常输入下崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:56:58