【问题标题】:How to find certain substring in string and then go back to certain character?如何在字符串中找到某个子字符串然后返回某个字符?
【发布时间】:2022-01-18 15:43:16
【问题描述】:

我将消息保存在字符串中,我需要创建过滤函数来在这些消息中查找用户指定的单词。我已将每条消息按'\n' 拆分,因此一个聊天的示例是:

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

现在用户可以要求搜索单词up,我已经实现了这样的搜索:

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

我可以将该字符串放入字符串流中并使用getline\n,但是如何返回到以前的\n 以便获得完整消息?另外,第一条消息怎么办,因为它不是以\n开头的?

【问题讨论】:

  • 嗯...我想说是时候离开键盘,想知道你想对这些消息做什么。从概念上讲,您有一系列消息。您应该考虑一下每条消息应具有的属性以及您希望对其实现的操作。从那时起,您可以设计类并将您的 looong 字符串转换为这些类实例的列表或向量。与围绕简单字符串的非常聪明的意大利面条代码相比,这可能更清洁、更易于维护。

标签: c++ string


【解决方案1】:

既然你说你拆分了字符串,我想你有一个字符串向量,你想在其中找到 up 例如。你会做这样的事情

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

如果你没有在向量中分割字符串,你可以使用这个函数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;
}

如果此功能不起作用,您可以随时查看How do I iterate over the words of a string?

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 2013-05-04
    • 2011-05-28
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多