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

时间:2018-04-12 04:47:44

标签: 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;
}

我能够在第一次出现&#39; /&#39;之前获得子串。即我可以获得user但是如何在第二次出现&#39; /&#39;之后得到子字符串?即local以及最后一次出现的&#39; /&#39;即example没有扩展名.txt?如何有效地完成

3 个答案:

答案 0 :(得分:1)

在这种情况下使用strtok()有关详细description,请查看此链接!希望这有帮助!

答案 1 :(得分:1)

我不会使用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;
}

但正如您所看到的,它需要比第一个示例更多的代码。

答案 2 :(得分:0)

使用此:

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

#define MAXLEN 100

int main(void)
{
    char buf[] = "user/local/etc/bin/example.txt";
    char substring[MAXLEN+1];
    char *a, *b;
    int len;

    b = buf;                                   
    while ( (a = strchr(b, '/')) != NULL || (a = strchr(b, '.')) != NULL) 
    {
        len = a - b;                         
        if (len > MAXLEN)
            return 0;                             
        memcpy(substring, b, len);              
        substring[len] = 0;                         
        printf("'%s'\n", substring);   
        b = a + 1;                           
    }
    return 0;
}

这是输出:

'user'
'local'
'etc'
'bin'
'example'