檢查字符串是否包含另一串字符串(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;
}

如果您有更好的算法或者方法請私信或者評論我!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM