在 C++ 中使用循环查找字符串中的子字符串

find substring in a string with loops in c++

代码将从用户获取两个字符串并检查字符串,是否包含子字符串作为第二个输入。

    string st1;
    string subst1;
    string message = " ";
    cout << "Enter string and subst:";
    cin >> st1;
    cin >> subst1;

    for (int a=0; a < st1.length(); a++) {
        if (st1[a] == subst1[0]) {
            for (int k = 0; k < subst1.length(); k++) {
                if (st1[a + k] == subst1[k])
                    message = "True";
                else
                    message = "False";
            }
        }
    }
    cout << message;

此代码不适用于 "alice" 和 "ba" 等输入。输出应该是false 但是当我执行代码程序的时候直接结束了

为什么不使用 find()

string st1, subst1, message=" ";
cout<<"Enter string and subst:";
cin>>st1>>subst1;
if (st1.find(subst)==string::npos) 
    message="Not found"; 
else message ="Found"; 

如果您不允许使用这种方法,那么我向您提出以下建议:

string st1, subst1, message=" ";
bool found=false; 
cout<<"Enter string and subst:";
cin>>st1 >>subst1;

for (int a=0; !found && a<st1.length();a++) {
    if (st1[a]==subst1[0]) {
        found = true;  // there's some hope 
        for (int k=0; found && k<subst1.length(); k++) {
           if (a+k>=st1.length() || st1[a+k]!=subst1[k])  // oops! might overflow or fail
                 found = false;   // this will also end the inner loop
        }
    }
}
message = found ?  "True":"False";
cout<< message<<endl;

原则是要使比较成功,所有字符必须相等。但是如果单个字符失败,你应该停止失败的比较。

这里是live demo

因为有些情况下a+k超过了字符串st1的长度:

if (st1[a + k] == subst1[k]) {
    message = "True";
}

在执行这条语句之前,验证是否 a + k < st1.length()

但还有一点: 当 message 变为 False 时,您必须停止比较,否则变量 message 可能再次 True.