C++ 分析括号之间的字符串
我有一个字符串是这样的:C++ 分析括号之间的字符串,c++,string,C++,String,我有一个字符串是这样的: Room -> Subdiv("X", 0.5, 0.5) { sleep | work } : 0.5 我需要以某种方式提取{}之间的两个字符串,即睡眠和工作。格式很严格,括号之间只能有两个单词,但单词可以更改。括号前后的文本也可以更改。我最初的做法是: string split = line.substr(line.find("Subdiv(") + _count_of_fchars); split = split.substr(4, axis.find("
Room -> Subdiv("X", 0.5, 0.5) { sleep | work } : 0.5
我需要以某种方式提取{}
之间的两个字符串,即睡眠
和工作
。格式很严格,括号之间只能有两个单词,但单词可以更改。括号前后的文本也可以更改。我最初的做法是:
string split = line.substr(line.find("Subdiv(") + _count_of_fchars);
split = split.substr(4, axis.find(") { "));
split = split.erase(split.length() - _count_of_chars);
然而,我确实意识到,如果将方括号中的字符串更改为任何不同长度的字符串,这将不起作用
如何做到这一点?谢谢 类似于:
unsigned open = str.find("{ ") + 2;
unsigned separator = str.find(" | ");
unsigned close = str.find(" }") - 2;
string strNew1 = str.substr (open, separator - open);
string strNew2 = str.substr (separator + 3, close - separator);
无需硬编码任何数字:
- 查找
作为字符串末尾第一个A
的索引,向后搜索“{”
- 从
的位置查找“{”
作为第一个B
的索引,向前搜索“|”
- 从
的位置查找“|”
作为第一个C
“}”的索引,向前搜索
B
和A
之间的子字符串为您提供第一个字符串。而C
和B
之间的子字符串为您提供第一个字符串。您可以在子字符串搜索中包含空格,也可以稍后将其取出
std::pair<std::string, std::string> SplitMyCustomString(const std::string& str){
auto first = str.find_last_of('{');
if(first == std::string::npos) return {};
auto mid = str.find_first_of('|', first);
if(mid == std::string::npos) return {};
auto last = str.find_first_of('}', mid);
if(last == std::string::npos) return {};
return { str.substr(first+1, mid-first-1), str.substr(mid+1, last-mid-1) };
}
尽管您说要查找的单词数量是固定的,但我使用正则表达式制作了一个更灵活的示例。不过,您仍然可以使用Мц的答案获得相同的结果
std::string s = ("Room -> Subdiv(\"X\", 0.5, 0.5) { sleep | work } : 0.5")
std::regex rgx("\\{((?:\\s*\\w*\\s*\\|?)+)\\}");
std::smatch match;
if (std::regex_search(s, match, rgx) && match.size() == 2) {
// match[1] now contains "sleep | work"
std::istringstream iss(match[1]);
std::string token;
while (std::getline(iss, token, '|')) {
std::cout << trim(token) << std::endl;
}
}
std::string s=(“房间->子视窗(\'X\',0.5,0.5){sleep | work}:0.5”)
std::regex rgx(“\\{((?:\\s*\\w*\\s*\\\\\\\\\\?)+)\}”);
std::smatch匹配;
if(std::regex_搜索(s,match,rgx)&&match.size()=2){
//匹配[1]现在包含“睡眠|工作”
标准::istringstream iss(匹配[1]);
字符串标记;
while(std::getline(iss,token,“|”)){
STD::CUTE查找<代码> {<代码> >查找<代码> } /代码>在代码> > {…<代码>之间取子块,在<代码> > } /代码>之间取子块。@ VITTRORORMOO好主意!我的C++词汇真的是瓶颈!谢谢!
或者字数可以改变吗?@muXXmit2X不只是两个字。但是字数可以改变!格式很严格!
std::string s = ("Room -> Subdiv(\"X\", 0.5, 0.5) { sleep | work } : 0.5")
std::regex rgx("\\{((?:\\s*\\w*\\s*\\|?)+)\\}");
std::smatch match;
if (std::regex_search(s, match, rgx) && match.size() == 2) {
// match[1] now contains "sleep | work"
std::istringstream iss(match[1]);
std::string token;
while (std::getline(iss, token, '|')) {
std::cout << trim(token) << std::endl;
}
}