【问题标题】:How to split a path into separate strings?如何将路径拆分为单独的字符串?
【发布时间】:2014-09-04 06:09:55
【问题描述】:

这是一个免费的问题:
How to build a full path string (safely) from separate strings?

所以我的问题是,如何以跨平台的方式将路径拆分为单独的字符串。

这个solution,使用Boost.Filesystem非常优雅,Boost一定实现了一些splitPath()函数。我找不到。

注意: 请记住,我可以自己完成这项任务,但我对封闭式解决方案更感兴趣。

【问题讨论】:

  • 您是要拆分路径的所有部分,还是仅拆分文件名中的父目录?
  • @idanshmu : 你能提供一些 i/p 和 o/p 的样本吗?
  • 你看path::iterator了吗?

标签: c++ boost path split cross-platform


【解决方案1】:

确实有path_iterator。但如果你想要优雅:

#include <boost/filesystem.hpp>

int main() {
    for(auto& part : boost::filesystem::path("/tmp/foo.txt"))
        std::cout << part << "\n";
}

打印:

"/"
"tmp"
"foo.txt"

    for(auto& part : boost::filesystem::path("/tmp/foo.txt"))
        std::cout << part.c_str() << "\n";

打印

/
tmp
foo.txt

无需担心运动部件

【讨论】:

    【解决方案2】:
    std::vector<std::string> SplitPath(const boost::filesystem::path &src) {
        std::vector<std::string> elements;
        for (const auto &p : src) {
            elements.emplace_back(p.filename());
        }
        return elements;
    }
    

    【讨论】:

    • 实际上,在发布此答案时,我仍在输入和编译示例。
    • 如果elements 的类型为vector&lt;string&gt;,你应该写elements.emplace_back(p.filename().string())
    【解决方案3】:

    如果你没有 C++11 auto,或者正在编写跨平台代码,其中 boost::filesystem::path 可能是 std::wstring:

    std::vector<boost::filesystem::path> elements;
    for (boost::filesystem::path::iterator it(filename.begin()), it_end(filename.end()); it != it_end; ++it) 
    {
        elements.push_back(it->filename());
    }
    

    【讨论】:

      【解决方案4】:

      如果您想在不使用任何库的情况下手动完成所有操作,那么这将有所帮助。 它将给定的完整路径拆分为相应的名称并将它们存储在一个向量中。

      #include <iostream>
      #include <string>
      #include <vector>
      using namespace std;
      
      int main()
      {
          string filePath = "C:\\ProgramData\\Users\\CodeUncode\\Documents";
          vector<string> directories;
          size_t position=0, currentPosition=0;
          
          while(currentPosition != -1)
          {
              currentPosition = filePath.find_first_of('\\', position);
              directories.push_back(filePath.substr(position,currentPosition-position));
              position = currentPosition+1;
          }
          for(vector<string>::iterator it = directories.begin(); it!=directories.end(); it++)
              cout<<*it<<endl;
      
          return 0;
      } 
      

      输出:

      C:
      ProgramData
      Users
      CodeUncode
      Documents
      

      【讨论】:

      • 您发布了相同的(糟糕的)代码here。最好不要发布多个问题的“重复”答案……考虑删除一个答案并改进另一个答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      相关资源
      最近更新 更多