首页 > 解决方案 > 控制一个字符串是否存在于另一个字符串中(在 C++ 中)

问题描述

如何确定给定字符串是否完全包含另一个子字符串?
我可以使用的库和函数不受限制,我只需要最简单的解决方案即可。

带有一些输入的示例:

string str1 = "helloworld"; //master string
string str2 = "low"; //substring
std::cout << contains(str1, str2); //should print True, "low" is in "helloworld"
string str1 = "hello-world"; //master string
string str2 = "low"; //substring
std::cout << contains(str1, str2); //should print False, "low" is NOT present in "hello-world"

标签: c++string

解决方案


#include <iostream>
#include <string.h>

using namespace std;

bool contains(char *sub, char *whole);

int main(void)
{
    char sub[]  = "hello";
    char sub2[] = "hey";

    char whole[]= "well hello world";

    if(contains(sub, whole))
        cout << "it does" << endl;
    else
        cout << "it does not" << endl;

    if(contains(sub2, whole))
        cout << "it does" << endl;
    else
        cout << "it does not" << endl;

    return 0;
}

bool contains(char *sub, char *whole)
{
    for(int i=0 ; i<strlen(whole) ; i++)
    {
        bool match=true;
        for(int j=0 ; j<strlen(sub) ; j++)
        {
            if(sub[j] != whole[j+i])
                match = false;
        }
        if(match)
            return true;
    }

    return false;
}

推荐阅读