zoukankan      html  css  js  c++  java
  • 检查字符串是否包含另一串字符串(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;
    }
    

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

  • 相关阅读:
    VirtualBox安装
    记一次修改fstab挂载参数
    Debian其实有提供附带了各种桌面的安装镜像
    记一次使用unzip命令
    记一次给iPhone 6越狱
    浅谈.Net中内置的一种特殊的引用类型 -- String类型
    .Net中的静态类和非静态类、静态成员和非静态成员
    .Net子窗体给父窗体传值的几种方法
    int、float、double In .Net之相互转换
    车厢重组
  • 原文地址:https://www.cnblogs.com/qscgy/p/13358130.html
Copyright © 2011-2022 走看看