0

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?

qu4lizz
  • 317
  • 2
  • 12
  • Hmm... I would say that it is time to get away from the keyboard and wonder what you want to do with those *messages*. Conceptually, you have a sequence of messages. You should think a moment about what attributes each message should have and actions you would like to realize on it. From that point you could design classes and convert your looong string to a list or vector of instances of those classes. That could be cleaner and easier to maintain than a very clever spaghetti code around a simple string. – Serge Ballesta Jan 18 '22 at 16:05

1 Answers1

1

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?

Robin Dillen
  • 704
  • 5
  • 11