#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/