Home > Software design >  How to find certain substring in string and then go back to certain character?
How to find certain substring in string and then go back to certain character?

Time:01-19

I save messages in string and I need to make filter function that finds user specified word in those messages. I've split each message by '\n' so the example of one chat would be:

user1:Hey, man\nuser2:Hey\nuser1:What's up?\nuser2:Nothing, wbu?\n etc.

Now user could ask to search for word up and I've implemented a search like this:

for (auto it = msg.cbegin(); (it = std::find(it, msg.cend(), str)) != msg.cend(); it  )

and I could put that string into stringstream and use getline to \n, but how do I go backwards to previous \n so I can get full message? Also, what about first message, cause it doesn't start with \n?

CodePudding user response:

Since you said you split the strings, I image you have a vector of strings where you want to find up for example. You would do something like this

for (const auto& my_string: vector_of_strings){
    if (my_string.find("up") != string::npos) { 
        // message containing up is my_string
    }
}

In case you haven't split the strings in a vector you can use this func inspired by this:

vector<string> split(const string& s, const string& delimiter){
    vector<string> ret;
  size_t last = 0;
  size_t next = 0;
  while ((next = s.find(delimiter, last)) != string::npos) {
      ret.emplace_back(s.substr (last, next - last));
      last = next   1;
    }
  ret.emplace_back(s.substr(last));
  return ret;
}

If this function doesn't work you can always take a look at How do I iterate over the words of a string?

  •  Tags:  
  • Related