繁体   English   中英

如何在 C++ 的向量中的另一个字符串中找到一个字符串/字符? [这对我行得通]

[英]How do you find a string/char inside another string that's in a vector in C++? [that works for me]

我在多个论坛页面上查找了这一点,而不仅仅是堆栈溢出,并尝试了“检查字符串是否包含 C++ 中的字符串”帖子以及其他解决方案,并尝试了几乎所有提出的解决方案,但似乎都没有为我工作? 我尝试了vector[i].find(std::string2)以及if(strstr(s1.c_str(),s2.c_str())) {cout << " S1 Contains S2";}以及

 std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
                     " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
    std::string needle = "pisci";
    auto it = std::search(in.begin(), in.end(),
                   std::boyer_moore_searcher(
                       needle.begin(), needle.end()));
    if(it != in.end())
        std::cout << "The string " << needle << " found at offset "
                  << it - in.begin() << '\n';
    else
        std::cout << "The string " << needle << " not found\n";

以及更多解决方案(适用于我的代码),但没有一个有效。 我唯一没有尝试的是std::string.contain()但那是因为视觉工作室(2019 v.142 - 如果有帮助)[我正在使用的 C++ 标准语言,预览 - 最新 C++ 工作草案的功能(std:c++latest),] 无法识别 function -因为由于某种原因它无法识别更大的库。 我什至尝试颠倒这两个变量,以防我将两者混合在一起,并在较小的变量中寻找较大的变量。

我是 C++ 的新手,所以我不擅长解决这样的问题,所以请原谅我的无知。 出现问题是因为我正在寻找的是向量吗? 我创建了一个vector <string> names = {"Andrew John", "John Doe",}; 里面有名字,我试图“窥视”它并找到关键字,但同样,没有任何效果。 在向量中寻找东西时,是否有特殊的 function 可以调用? 任何帮助将不胜感激!

如何在 C++ 的向量中的另一个字符串中找到一个字符串/字符?

如果std::vector<std::string>没有排序,我会使用std::find_if

例子:

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

int main() {
    // A vector with some strings:
    std::vector<std::string> vec{
        {"Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
         " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"},
        {"Foo bar"}};
                     
    std::string needle = "pisci";
    
    auto it = std::find_if(vec.begin(), vec.end(),
                          [&needle](const std::string& str) {
                              return str.find(needle) != std::string::npos;
                          });

    if(it != vec.end()) {
        std::cout << "Found needle in string:\n" << *it << '\n';
    }
}

您的示例代码与您的文字描述不符。 您不是在搜索字符串向量,而是搜索字符串。 实际上,它似乎是基于 CPPreference 中的示例。

在 position 43 处找到针
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

当我尝试它时它会起作用。

这对您的搜索可能有点过分,因为您只搜索字符串一次。 使用简单的find可能会更好。

这根本没有显示的是你希望它在一个循环中,用字符串向量in的每个值替换。 这是一个简单for循环:

for (const auto& in : myvector) { ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM