Get a file name from a path

前端 未结 21 1572
面向向阳花
面向向阳花 2020-11-30 23:55

What is the simplest way to get the file name that from a path?

string filename = \"C:\\\\MyDirectory\\\\MyFile.bat\"

In this example, I s

21条回答
  •  情深已故
    2020-12-01 00:17

    A possible solution:

    string filename = "C:\\MyDirectory\\MyFile.bat";
    
    // Remove directory if present.
    // Do this before extension removal incase directory has a period character.
    const size_t last_slash_idx = filename.find_last_of("\\/");
    if (std::string::npos != last_slash_idx)
    {
        filename.erase(0, last_slash_idx + 1);
    }
    
    // Remove extension if present.
    const size_t period_idx = filename.rfind('.');
    if (std::string::npos != period_idx)
    {
        filename.erase(period_idx);
    }
    

提交回复
热议问题