【问题标题】:how do i find all the positions of substring in a string c++ programming如何在字符串 C++ 编程中找到子字符串的所有位置
【发布时间】:2015-06-15 20:45:26
【问题描述】:

我有代表按键事件的字符串(c++ 编程):X、Y、DEL 当且仅当收到事件 X 时,我必须打印“X”,但没有 Y 事件在两个事件之前或之后发生。

例如:

  1. “DEL DEL X DEL DEL Y” => 输出“X”

  2. "DEL DEL X DEL Y DEL" => 没有输出

  3. "Y DEL X DEL DEL DEL" => 没有输出

  4. “X X X X X X”=> 输出“XXXXXX”

我该怎么做? 我很难解析和搜索字符串 谢谢

【问题讨论】:

  • @TalShalti 编辑好。更具可读性。
  • 如果发现 Y 附近没有 X 怎么办?打印 Y?
  • 我只需要打印 X(在上述条件下)。我不得不忽略 Y。

标签: c++ string-parsing


【解决方案1】:

一个简单的解析器:

#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);
    }
}

示例用法:

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
}

operate on keys 是最难的部分:使用键列表,您需要弄清楚要输出什么。返回一些代码,我们可以帮助您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2017-11-20
    • 2012-08-03
    • 1970-01-01
    • 2017-10-02
    • 2012-05-21
    • 2022-07-16
    相关资源
    最近更新 更多