当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
Getting a word or sub string from main string when char '' from RHS is found and then erase rest
假设我有一个字符串,如下所示
输入 = " \\路径\我的文件 这是我的刺">
输出 = 我的文件
当找到第一个字符"\"时,从 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;
}
注意:注意转义序列,单个反斜杠写为字符串文本中的"\"
。
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取