• 检查字符串是否包含另一串字符串(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.
    ";
        else
            std::cout << "Second string is not a substring of the first string.
    ";
    
        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;
    }
    

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

  • 相关阅读:
    Android 开发转型前端准备知识
    atom写文档技巧
    gerrit升级到16.04之后连接不到服务器
    adb shell am pm
    ArrayList和LinkedList的区别
    Android源码编译
    Android动态加载代码技术
    File 与 FileStream 文件运用
    物体在一定范围自有碰撞
    扫描二维码加载网页图片
  • 原文地址:https://www.cnblogs.com/qscgy/p/13358130.html
Copyright © 2020-2023  润新知