用/分割C ++字符串

问题描述 投票:2回答:3

我在C ++中有这样的字符串:"dirname/filename.ini"。我需要在/之后得到所有东西。我该怎么办?

c++ string
3个回答
12
投票

使用find中的substrstd::string方法。

std::string fullpath = "dirname/filename.ini";
int beginIdx = fullpath.rfind('/');
std::string filename = fullpath.substr(beginIdx + 1);

7
投票

要由Luchian回答,如果路径可以包含正斜杠或反斜杠字符,请使用std::string::find_last_of()

std::string::find_last_of()

0
投票

这是我用来分割字符串的方法。它也适用于多次出现的定界符:

const int idx = fullpath.find_last_of("\\/");
if (std::string::npos != idx)
{
    std::string filename(fullpath.substr(idx + 1);
}
© www.soinside.com 2019 - 2024. All rights reserved.