可以使用字符串分割函数和字符串数组来实现。

示例代码:

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string path = "/usr/local/bin/";
    std::vector<std::string> pathArray;
    std::string delimiter = "/";
    size_t pos = 0;
    std::string token;
    while ((pos = path.find(delimiter)) != std::string::npos) {
        token = path.substr(0, pos);
        pathArray.push_back(token);
        path.erase(0, pos + delimiter.length());
    }
    if (!path.empty()) {
        pathArray.push_back(path);
    }
    std::cout << "The last string in the path is: " << pathArray.back() << std::endl;
    return 0;
}

输出结果:

The last string in the path is: bin

这里使用了字符串分割函数 find()substr(),以及字符串数组 vector 来存储分割后的字符串。最后输出数组中最后一个元素即为路径最前一个字符串。

C++ 获取路径最后一个字符串的方法

原文地址: https://www.cveoy.top/t/topic/mQYE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录