【问题标题】:Find all instances of string in anotherstring在另一个字符串中查找字符串的所有实例
【发布时间】:2015-05-13 01:58:43
【问题描述】:

下面我有一段比较两个字符串的代码。

if (long.find(short) != string::npos) {
        cout << "FOUND";
}

这只告诉我它是否在长字符串中找到了短字符串。但是我怎样才能找到所有的实例并告诉用户这些字符串的实例显示在哪里呢?

我的想法可能是让它成为一个循环,但我无法实现它。

【问题讨论】:

标签: c++ string loops find


【解决方案1】:

你可以这样做

#include <iostream>
#include <string>

int main()
{
    std::string test = "we are searching for searching here";
    std::string str = "searching";
    std::string::size_type start = test.find(str); // find the first instance
    while(start != std::string::npos) // repeat for the rest
    {
        std::cout << "Found on pos: " << start << std::endl;
        start = test.find(str, start + 1);
    }
}

旁注:不要使用 longshort 作为字符串名称,因为它们是 C++ 保留关键字。

【讨论】:

    【解决方案2】:

    find 的重载之一允许您告诉它从哪里开始查找。因此,在找到一个匹配项后,再次调用 find(),将之前的位置加一。

    【讨论】:

      【解决方案3】:

      这里是一个示例实现:

      #include<iostream>
      #include<string>
      
      int main() 
      {
         std::string long_str ("abcabcabcabc");
         std::string short_str("abc"); 
         while( true)
         {
            std::size_t found = long_str.find(short_str);
            if (found == std::string::npos)
              break;
            long_str = long_str.substr(found+short_str.length());
            std::cout<<long_str<<"\n";
         }
      }
      

      输出:

      abcabcabc

      abcabc

      abc

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-03
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2022-12-15
        • 1970-01-01
        • 2022-06-17
        相关资源
        最近更新 更多