#include <iostream> #include <string> #include <sstream> #include <vector> // 函数用于按照指定分隔符分割字符串 std::vector<std::string> splitString(const std::string &s, char delim) { std::vector<std::string> tokens; std::stringstream ss(s); std::string token; while (std::getline(ss, token, delim)) { tokens.push_back(token); } return tokens; } int main() { std::string fullPath = "/home/dongdong/2project/0data/NWPU/config/config.yaml"; // 按照 '/' 分割字符串 std::vector<std::string> parts = splitString(fullPath, '/'); // 获取前面的部分,组装成路径 std::string result; for (int i = 0; i < parts.size() - 1; ++i) { result += parts[i] + '/'; } // 打印结果 std::cout << "Extracted path: " << result << std::endl; return 0; }
cmake_minimum_required(VERSION 3.5) project(PathExtraction) # 设置 C++ 标准 set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) # 添加可执行文件生成规则 add_executable(PathExtraction main.cpp)
标签:std,字符,string,截取,c++,tokens,token,parts,include From: https://www.cnblogs.com/gooutlook/p/18339767