简体   繁体   中英

Split string and get values before different delimiters

Given the code:

procedure example {
  x=3;
  y = z +c ;
  while p {
    b = a+c ;
  }
}

I would like to split the code by using the delimiters { , ; , and } . After splitting, I would like to get the information before it together with the delimiter.

So for example, I would like to get procedure example { , x=3; , y=z+c; , } . Then I would like to push it into a list<pair<int, string>> sList . Could someone explain how this can be done in c++?

I tried following this example: Parse (split) a string in C++ using string delimiter (standard C++) , but I could only get one token. I want the entire line. I am new to c++, and the list, splitting, etc. is confusing.

Edit: So I have implemented it, and this is the code:

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

However, it seems that it can't separate based on semicolon separately, openBracket and closeBracket. Anyone knows how to separate based on these characters individually?

2nd Edit: I have done this (codes below). It is separating correctly, I have one for open curly bracket. I was planning on adding the value to the list in the commented area below. However, when i think about it, if i do that, then the order of information in the list will be messed up. As i have another while loop which separates based on open curly bracket. Any idea on how i can add the information in an order?

Example: 
 1. procedure example {
 2. x=3;
 3. y = z+c
 4. while p{

and so on.

while (semiColon != string::npos) {
        semiColon++;
        //add list here
        semiColon = lines.find(';',semiColon);
    }

I think that you should read aboutstd::string::find_first_of function .

Searches the string for the first character that matches any of the characters specified in its arguments.

I have a problem to understand what you really want to achieve. Let's say this is an example of the find_first_of function use.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM