How to get file extension from string in C++

前端 未结 25 2428
迷失自我
迷失自我 2020-11-30 22:35

Given a string \"filename.conf\", how to I verify the extension part?

I need a cross platform solution.

25条回答
  •  遥遥无期
    2020-11-30 23:31

    actually the STL can do this without much code, I advise you learn a bit about the STL because it lets you do some fancy things, anyways this is what I use.

    std::string GetFileExtension(const std::string& FileName)
    {
        if(FileName.find_last_of(".") != std::string::npos)
            return FileName.substr(FileName.find_last_of(".")+1);
        return "";
    }
    

    this solution will always return the extension even on strings like "this.a.b.c.d.e.s.mp3" if it cannot find the extension it will return "".

提交回复
热议问题