Split string by multiple pair of brackets.

Sep 30, 2018 at 5:49pm
Hi everyone!

I have my example string is:
(if: $debug is true)[When you get your grade back, you smile smugly--an A+!][You missed the due date and got an F. Lame. (if: $facebook is true)] At least your friends took you out to cheer you up.


My problem is to tokenize string into section by their brackets.
So I want to split it by their type:
- Command: start and end with round bracket
- Block: start and end with square bracket.
- Link: start and end with double square bracket.
- Text is the part doesn't contain in any bracket
*If one type has another type inside, we skip the one inside.

This is what I have done:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main() {
    string s = "(if: $debug is true)[When you get your grade back, you smile smugly--an A+!][You missed the due date and got an F.  Lame.  (if: $facebook is true)] At least your friends took you out to cheer you up.";
    vector<string> token;
    string tok;
    stringstream ss(s);
    string deLim = "()[]";
    string line;

    while (getline(ss, line)){
        size_t prev = 0, pos ;
        while ((pos = line.find_first_of(deLim, prev)) != std::string::npos)
        {
            if (pos > prev){
                tok = line.substr(prev, pos - prev);
                token.push_back(tok);
            }
            prev = pos+1;
        }
    }

    for (const auto &i : token) {
        cout << i << endl;
    }

    return 0;
}


However,I'm pretty sure my solution is wrong, because It can't be able to track the brackets.

Is there any other way to do it?
Last edited on Sep 30, 2018 at 5:50pm
Topic archived. No new replies allowed.