控制一个字符串是否存在于另一个字符串中(在C ++中)

时间:2019-04-03 08:14:46

标签: c++ string

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

带有一些输入的示例:

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"

1 个答案:

答案 0 :(得分:-1)

#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;
}