在c++中查找带有循环的字符串中的子字符串

find substring in a string with loops in c++

本文关键字:字符串 循环 c++ 查找      更新时间:2023-10-16

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

    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"answers"ba"这样的输入。输出应该是false,但当我执行代码程序时,直接结束

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

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

在执行该语句之前,请验证a + k < st1.length()

但另一句话:当message变为False时,必须停止比较,否则变量message可能再次变为True

为什么不使用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;

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

这里是的实时演示