[英]Splitting a C++ String with /
我在 C++ 中有一個這樣的字符串: "dirname/filename.ini"
。 我需要在/
之后獲取所有內容。
我怎樣才能做到這一點?
使用std::string
中的find
和substr
方法。
std::string fullpath = "dirname/filename.ini";
int beginIdx = fullpath.rfind('/');
std::string filename = fullpath.substr(beginIdx + 1);
要擴展 Luchian 的回答,如果路徑可以包含正斜杠或反斜杠字符,請使用std::string::find_last_of()
:
const int idx = fullpath.find_last_of("\\/");
if (std::string::npos != idx)
{
std::string filename(fullpath.substr(idx + 1);
}
這就是我用來分割字符串的東西。 它也適用於多次出現的定界符:
char delimiter = '/';
std::string tmp = "", originalString = "this/might/be/it";
std::vector<std::string> parts;
std::istringstream iss(originalString);
while(std::getline(iss, tmp, delimiter)) {
parts.push_back(tmp);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.