从字符串 c++ 的末尾开始按字符拆分字符串

Split string by character starting from the end of the string c++

本文关键字:字符串 字符 拆分 开始 c++      更新时间:2023-10-16

我正在尝试从具有完整路径的字符串文件名创建一些文件夹。

    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