Search code examples
c++stringparsingapostrophe

Parsing out a string that contains two Apostrophe's


string test = "F'XSXESS'";

How would I go about parsing out F'XSXESS' so that it grabs the information inside the Apostrophe's(XSXESS)?

The output should be XSXESS.

Any idea's on how I should do this?

Thank you for any help you can provide!


Solution

  • What you basically want to do is, going though all the characters in the string and switch the parsing state at specific events (in your case an encounter of \').
    Here a small example:

    int main() {
        std::string test = "FFF'XSXSXSX'FFFFF";
    
            std::string result;
            bool state = 0;
            for(int i = 0; i < test.length(); i++) {
                if(test.at(i) == '\'') {
                    state = !state;
                    continue;
                }
                if(state)
                    result.push_back(test.at(i));
            }
            std::cout << result << std::endl;
        return 0;
    }
    

    For the sake of simplicity I've chosen a bool to describe my current state. This code is probably still not the best solution because this would also parse FF'XX'FFFF'CC' to FFCC. You could solve this problem by adding an "exit"-state, that indicates the end of the parsing process.
    Hope I could help.