c - 如何从 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()
提取子字符串的位置this
,strchr(filepath, '/')
现在我需要提取其余的子字符串is/my/path/to/file.jpg
解决方案
将所有内容复制到文件名,然后附加'\0'
:
int pathLen = filename - filepath;
char *path = (char *) malloc(pathLen + 1);
memcpy(path, filepath, pathLen);
path[pathLen] = '\0';
...
free(path);
推荐阅读
- javascript - 从 Acrobat JavaScript 中的 extractPages 中排除页面
- android - 如何在 for 循环中使用动态键值从 JSON 数组获取值?科特林
- json - 在 TOIT 语言上对 JSON 对象进行序列化/反序列化
- node.js - 为什么在 Node.js 中发送响应后函数没有显式返回?
- python - 使用 matplotlib 绘制函数
- javascript - 使用jquery和ajax调用php文件将数据加载到多个div中
- python - 使用 boruta 和支持向量回归执行特征选择时遇到问题
- java - 正则表达式与?对于一组词
- c# - Mono WebSocket 服务器冻结 5 分钟
- android - 与本机反应的领域数据同步