假设我有一个字符串,如下所示
输入 = " \\路径\我的文件 这是我的刺">
输出 = 我的文件
当找到第一个字符"\"时,从 RHS 获取单词(即 MYFILES(并删除其余部分。
以下是我累了的方法,但它很糟糕,因为存在运行时错误,因为中止以内核终止。
请建议从上述字符串中仅获取一个单词(即 MYFILES(的最干净和/或最短的方法?
我有搜索并从最近两天开始尝试,但没有运气,请帮忙
注意:上面示例中的输入字符串不是硬编码的,因为它应该是。该字符串包含动态更改,但字符"\"肯定可用。
std::regex const r{R"~(.*[^\]\([^\])+).*)~"} ;
std::string s(R"(" //PATH//MYFILES This is my sting "));
std::smatch m;
int main()
{
if(std::regex_match(s,m,r))
{
std::cout<<m[1]<<endl;
}
}
}
要擦除字符串的一部分,您必须找到该部分的开始和结束位置。在std::string
中找到 somethig 非常容易,因为该类有六种内置方法(std::string::find_first_of
、std::string::find_last_of
等(。下面是一个如何解决问题的小示例:
#include <iostream>
#include <string>
int main() {
std::string input { " \PATH\MYFILES This is my sting " };
auto pos = input.find_last_of('\');
if(pos != std::string::npos) {
input.erase(0, pos + 1);
pos = input.find_first_of(' ');
if(pos != std::string::npos)
input.erase(pos);
}
std::cout << input << std::endl;
}
注意:注意转义序列,单个反斜杠写为字符串文本中的"\"
。