首页 > 解决方案 > 如何从 strrchr() 或 strchr() 中提取剩余的子字符串?

问题描述

假设我有以下看起来像文件路径的字符串:

 char *filepath = "this/is/my/path/to/file.jpg";

我可以strrchr()用来提取file.jpg如下:

 char *filename =  strrchr(filepath, '/') + 1;

现在我需要提取并存储字符串的其余部分this/is/my/path/to。我如何以最有效的方式做到这一点?请注意,我想避免使用strtok()orregex或大的迭代循环。

如果:

我可以将相同的子字符串提取技术应用于strchr()提取子字符串的位置thisstrchr(filepath, '/')现在我需要提取其余的子字符串is/my/path/to/file.jpg

标签: cstringstring.hstrrchr

解决方案


将所有内容复制到文件名,然后附加'\0'

int   pathLen = filename - filepath;
char *path = (char *) malloc(pathLen + 1);
memcpy(path, filepath, pathLen);
path[pathLen] = '\0';

...

free(path);

推荐阅读