从字符串 c++ 的末尾开始按字符拆分字符串
Split string by character starting from the end of the string c++
我正在尝试从具有完整路径的字符串文件名创建一些文件夹。
string str = "c:/temp/tmp/test.txt";
File_data data;
为此,我需要解析字符串并删除文件名。我想做的是从后面拆分字符串,以便我可以从创建的目录名称中删除文件名。
以下是我到目前为止所拥有的。我用"/"拆分字符串,然后对其进行改革,除了数组的最后一个元素。
char strArray[1000];
strncpy(strArray, str, sizeof(strArray));
char* objectArray[100] = {0};
unsigned int index = 0;
unsigned int secondIndex = 0;
objectArray[index] = strtok(strArray, "/");
while(objectArray[index] != 0)
{
++index;
objectArray[index] = strtok(0, "/");
}
while(objectArray[secondIndex] != 0)
{
if ((secondIndex - 1) != index)
{
data.name += objectArray[secondIndex];
data.name += "/";
}
++secondIndex;
}
虽然上面的代码在技术上有效,但我仍然需要在开始之前清空data.name
。我希望有一种更简单的方法来完成所有这些操作,以便我可以从字符串中删除文件名并从其余部分创建一个目录结构。
使用 substr 并从字符串中查找函数。Substr 获取位置和长度并返回子字符串。Find 获取要检查的字符或字符串值,并将迭代器返回到实例(分别是查找第一个和最后一个实例的第一个和最后一个)。
在代码中执行以下操作:
auto pos = path.find_last_of ('/');
if (pos != string::npos) {
directory = path.substr (0,pos);
file = path.substr (pos);
}
在电话上这样做,所以为丑陋的答案道歉! :P
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度