c - 如何在c中多次出现 '/'时使用strchr获取子字符串并将其存储在变量中

标签 c

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

int main()
{

    char buf[50] = "user/local/etc/bin/example.txt";
    char* ptr;
    ptr = strchr(buf, '/');
    char path[20];
    strncpy(path, buf, ptr-buf);
    path[ptr-buf] =0;
    printf("%s\n", path);
    return 0;
}

我能够在第一次出现“/”之前获取子字符串,即我可以获得 user 但如何在第二次出现“/”之后获取子字符串,即 local 以及“/”的最后一次出现,即没有扩展名 .txt 的 example?怎样才能高效的完成呢

最佳答案

我不会为此使用 strchr。问题是 strchr 只能找到一个特定字符,但您同时关心 / 相反,我会使用指针迭代字符串,检查循环内的两个字符..

类似于:

int main()
{
    char buf[50] = "user/local/etc/bin/example.txt";
    char* pStart = buf;
    char* pCurrent = buf;
    while(*pCurrent != '\0')
    {
        if (*pCurrent == '/' || *pCurrent == '.') 
        {
            char str[20] = {0};
            strncpy(str, pStart, pCurrent - pStart);
            printf("%s\n", str);    
            pStart = pCurrent+1;
        }
        ++pCurrent;
    }
    return 0;
}

输出:

user
local
etc
bin
example

如果你真的想使用 strchr 来做到这一点,它可能是这样的:

int main()
{   
    char buf[50] = "user/local/etc/bin/example.txt";
    char* pStart = buf;
    char* pCurrent = strchr(pStart, '/');
    while(pCurrent != NULL)
    {
        char str[20] = {0};
        strncpy(str, pStart, pCurrent - pStart);
        printf("%s\n", str);    
        pStart = pCurrent+1;
        pCurrent = strchr(pStart, '/');
    }

    pCurrent = strchr(pStart, '.');
    if (pCurrent != NULL)
    {
        char str[20] = {0};
        strncpy(str, pStart, pCurrent - pStart);
        printf("%s\n", str);    
    }

    return 0;
}

但如您所见,它需要比第一个示例多一点的代码。

关于c - 如何在c中多次出现 '/'时使用strchr获取子字符串并将其存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49788179/

相关文章:

c - 作为 C 结构成员的函数指针

c - 如何查看多个用户组?

c++ - preread中偏移量的时间复杂度?

c++ - 什么是间接 goto 语句?

c - 如何正确初始化链表

C 套接字 : getsocketnane ip address is always 0. 0.0.0

c++ - 如何理解 C++ 中的 MNIST 二进制转换器?

c - 使用 TCP 客户端/服务器的生产者/消费者

python - 如何在 C 中编写一个函数,它将两个矩阵作为 numpy 数组的输入

c - 如何重新格式化一组文件中出现的所有换行符