分割字符串并在不同的分隔符之前获取值

Split string and get values before different delimiters

本文关键字:分隔符 获取 字符串 字符 串并 分割      更新时间:2023-10-16

给定代码:

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;
}