在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"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;
原则是,要使比较成功,所有字符必须相等。但是,如果单个字符失败,则应停止失败的比较。
这里是的实时演示
相关文章:
- 在循环C++中指定字符串之后,不会打印该字符串
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- C++-字符串是否包含一个带有简单循环的单词
- 在 c++ 中查找字符串中没有循环的数字总和
- 比较两个字符串后卡在无限循环中
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 而循环跳过 cin.getline() 对于 C 字符串
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 如何使用将字符串拆分为 for 循环中的变量的程序
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 循环访问还包含未使用元素的字符串数组
- 循环访问资源字符串表
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 修改向量中的字符串?(不使用循环)
- 试图突破字符串循环
- C++和Java的字符串循环性能比较
- 无法通过字符串循环我的程序以将其从英语翻译成猪拉丁语
- C++ 字符串循环检查相同的单词
- 为什么 javascript 中不使用字符串循环的C++语法?