分割字符串并在不同的分隔符之前获取值
Split string and get values before different delimiters
给定代码:
procedure example {
x=3;
y = z +c ;
while p {
b = a+c ;
}
}
我想通过使用分隔符{
, ;
和}
来分割代码。在分割之后,我想获得它之前的信息和分隔符。
例如,我想得到procedure example {
, x=3;
, y=z+c;
, }
。然后我想把它推到list<pair<int, string>> sList
。有人能解释一下这是如何在c++中实现的吗?
我尝试遵循以下示例:使用字符串分隔符(标准c++)在c++中解析(拆分)字符串,但我只能得到一个令牌。我要整条线。我是c++的新手,列表、拆分等让人困惑。
编辑:所以我已经实现了它,这是代码:size_t openCurlyBracket = lines.find("{");
size_t closeCurlyBracket = lines.find("}");
size_t semiColon = lines.find(";");
if (semiColon != string::npos) {
cout << lines.substr(0, semiColon + 1) + "n";
}
然而,它似乎不能根据分号分开,open括号和close括号分开。有人知道如何根据这些字符分开吗?
编辑2:我已经这样做了(代码如下)。它是正确的,我有一个左花括号。我打算在下面的评论区添加值到列表中。然而,当我想到它时,如果我这样做,那么列表中的信息顺序就会混乱。因为我有另一个while循环,它基于左花括号分开。我该如何在订单中添加信息?
Example:
1. procedure example {
2. x=3;
3. y = z+c
4. while p{
等等
while (semiColon != string::npos) {
semiColon++;
//add list here
semiColon = lines.find(';',semiColon);
}
我想你应该看看std::string::find_first_of函数
Searches the string for the first character that matches any of the characters specified in its arguments.
我很难理解你真正想要达到的目标。假设这是find_first_of
函数使用的一个示例。
list<string> split(string lines)
{
list<string> result;
size_t position = 0;
while((position = lines.find_first_of("{};n")) != string::npos)
{
if(lines[position] != 'n')
{
result.push_back(lines.substr(0, position+1));
}
lines = lines.substr(position+1);
}
return result;
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- C++获取两个分隔符之间的字符串并替换它
- 获取具有同一分隔符的多个实例的字符串的子字符串
- 推荐一种在未输入获取行分隔符时引发异常的方法?
- 如何阻止 cin.getline() 导致控制台在找不到分隔符时重复获取用户输入?
- 如何获取标准 C/C++ 中的文件分隔符符号:/ 或 \
- 如何使用分隔符获取所有第二个字段的总和
- 在分隔符之间获取字符串
- C++使用逗号作为分隔符的获取线多个变量类型
- 如何在C++中获取特定于平台的路径分隔符
- C++ 获取两个分隔符字符串之间的字符串
- 获取分隔符为/的给定字符串的最后一个目录的文本
- 使用 Boost.File system 获取平台的路径分隔符
- 分割字符串并在不同的分隔符之前获取值
- 使用stringstream获取行分隔符
- c++正则表达式.获取带分隔符的字符串