检查字符串是否包含另一串字符串(c++)

在c++中检查字符串是否包含另一串字符串,这个本来是我做过的一个算法题,不过最近刚好有个需求让我想到了这个题,就在此记录一下!

  1. 使用std::string::findfunction
string str ("There are two needles in this haystack.");
string str2 ("needle");

if (str.find(str2) != string::npos) {
//.. found.
//如果不等,则说明找到一样的,如果相等,则说明没找到,可以查看find的具体用法:http://www.cplusplus.com/reference/string/string/find/
} 
  1. 自己编写程序
#include <iostream>
#include <string>

bool CheckSubstring(std::string firstString, std::string secondString)
{
    if (secondString.size() > firstString.size())
        return false;

    for (int i = 0; i < firstString.size(); i++)
    {
        int j = 0;
        // If the first characters match
        if (firstString[i] == secondString[j])
        {
            int k = i;
            while (firstString[i] == secondString[j] && j < secondString.size())
            {
                j++;
                i++;
            }
            if (j == secondString.size())
                return true;
            else // Re-initialize i to its original value
                i = k;
        }
    }
    return false;
}

int main()
{
    std::string firstString, secondString;

    std::cout << "Enter first string:";
    std::getline(std::cin, firstString);

    std::cout << "Enter second string:";
    std::getline(std::cin, secondString);

    if (CheckSubstring(firstString, secondString))
        std::cout << "Second string is a substring of the frist string.\n";
    else
        std::cout << "Second string is not a substring of the first string.\n";

    return 0;
}
  1. 使用boost库,在boost中,你可以只使用boost::algorithm::contains:
#include "string"

#include "boost/algorithm/string.hpp"

using namespace std;
using namespace boost;
int main(){
    string s("Hello Word!");
    string t("ello");
    bool b = contains(s, t);
    cout << b << endl;
    return 0;
}

如果您有更好的算法或者方法请私信或者评论我!

posted @ 2020-07-21 23:30  zko  阅读(2680)  评论(0编辑  收藏  举报