如何在字符串 C++ 编程中找到子字符串的所有位置

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

本文关键字:字符串 位置 C++ 编程      更新时间:2023-10-16

我有字符串(C ++编程)表示按键事件:X,Y,DEL如果收到事件 X,我必须打印"X",但对于两个事件,没有 Y 事件之前或之后它。

例如:

  1. "DEL DEL X DEL Y " => 输出 "X"

  2. "DEL DEL
  3. X DEL Y DEL" => 无输出

  4. "Y DEL X DEL" => 无输出

  5. "X X X X X
  6. X X "=>输出"XXXXXX"

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

一个简单的

解析器:

#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是困难的部分:使用键列表,您需要弄清楚要输出的内容。回来提供一些代码,我们可以帮助您。