You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中按顺序检查std::vector元素是否存在于字符串中

问题解决:按顺序检查字符串中是否包含vector所有元素

你的代码问题在于每次查找子串都是从字符串开头开始,完全没考虑顺序——哪怕vector里的元素在输入字符串中是逆序出现,只要都存在就会返回true。要实现按顺序检查,需要跟踪每次查找的起始位置,确保下一个元素出现在上一个元素的后面。

修正后的代码如下:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    string input_str1 = "Good morning, hello, a beautiful world";//true
    string input_str2 = "what a wonderful world, hello!"; //false
    vector<string> item = {"hello", "world"};
    
    bool status = true;
    size_t current_pos = 0; // 跟踪当前查找的起始位置
    for (const auto& sub_item : item)
    {
        // 从current_pos开始查找子串
        size_t found_pos = input_str2.find(sub_item, current_pos);
        if (found_pos == string::npos)
        {
            status = false;
            break;
        }
        // 更新起始位置为找到的位置 + 子串长度,确保下一个元素在当前元素之后
        current_pos = found_pos + sub_item.length();
    }
    cout << boolalpha << status << endl;
    return 0;
}

关键改动说明

  • 新增current_pos变量,初始为0,记录每次查找的起始位置。
  • 调用string::find时传入第二个参数current_pos,限定查找范围是当前位置之后的字符串。
  • 找到子串后,将current_pos更新为found_pos + sub_item.length(),避免下一次查找匹配到当前子串的重叠部分,同时严格保证顺序。

测试input_str1时,会依次找到hello和之后的world,返回true;测试input_str2时,先找到world后,后续查找hello会从world的结束位置开始,找不到就返回false,符合预期。

内容的提问来源于stack exchange,提问作者4daJKong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:27:11