how do i find all the positions of substring in a string c++ programming

53 views Asked by At

I have string (c++ programming) that represent key press events: X, Y, DEL I have to print "X" if-and-only-if an event X was received, but no Y event preceded or succeeded it for two events.

For example:

  1. "DEL DEL X DEL DEL Y " => outputs "X"

  2. "DEL DEL X DEL Y DEL" => no outputs

  3. "Y DEL X DEL DEL DEL" => no outputs

  4. "X X X X X X "=> outputs "XXXXXX"

how should i do that? i got difficulty to parse and search the string thanks

1

There are 1 answers

0
user4581301 On

A simple parser:

#include<sstream> 
void parse(std::string input, std::vector<std::string> &keys)
{
    std::stringstream stream(input); // put input string into a stream for easy parsing 
    std::string key;
    while (stream >> key) // reads from the stream up to the first whitespace 
                          // or end of string
    {
        keys.push_back(key);
    }
}

Sample usage:

int main (int argc, char ** argsv)
{
    std::vector<std::string> keys; // allocate a container for the keys in the input
    // get input from unspecified source
    parse(input, keys); // call above function to fill the keys container with input 
    // operate on keys
}

The operate on keys is the hard part: With the list of keys, you need to figure out what to output. Come back with some code and we can help you out with it.