多个字符串:找到
Multiple string::find
是否有类似"if, for循环"之类的方法来搜索第一个字符串和第二个字符串,如果没有字符串出现,则搜索第三个字符串。
我被这三个困住了。我需要以某种方式检查第一个和第二个字符串中是否有"aba",但如果第三个字符串中没有"aba",就需要检查。一些想法?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s1, s2, s3;
string aba = "aba";
cout << "Input s1, s2: ";
cin >> s1;
cin >> s2;
s3 = s1 + s2;
cout << "String s3 is: " << s3;
cout << "nn****************************n";
size_t found = s1.find(aba);
if(found!=string::npos){
cout << "Have for s1.";
}
size_t found1 = s2.find(aba);
if(found1!=string::npos){
cout << "Have for s2.";
}
size_t found2 = s3.find(aba);
if(found2!=string::npos){
cout << "Have for s3.";
}
}
不知道你说的最好是什么意思,但保留你的变量名,这是稍微更干净。
if( ( found != string::npos ) && ( found1 != string::npos ) )
{
cout << "There is for s1 i s2.n";
}
else
{
cout << "Don't have for s1 i s2, search in s3.n";
if( found2 != string::npos )
{
cout << "There is for s3.n";
}
else
{
cout << "Don't have for s3.n";
}
}
,,操作符将短路,并且代码中没有重复的字符串。如果您需要更改字符串(尽管它看起来是一个玩具示例,我对此表示怀疑),您可以在一个地方完成它(DRY原则的一个小应用)。
终于做到了,但这是最好的方法吗?
if(found != string::npos){
if(found1 != string::npos){
cout << "nThere is for s1 i s2.";
} else {
cout << "nDon't have for s1 i s2, search in s3.";
if(found2 != string::npos){
cout << "nThere is for s3.";
} else {
cout << "nDon't have for s3.";
}
}
} else {
cout << "nDon't have for s1 i s2, search in s3.";
if(found2 != string::npos){
cout << "nThere is for s3.";
} else {
cout << "nDon't have for s3.";
}
}
相关文章:
- 如何在数组中找到字符串的长度
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 在文件中找到字符串后替换旁边的字符
- 如何在不使用字符串函数的情况下在char数组中找到字符串?(C )
- C unordered_map String键在存在时并不总是找到?字符串v char
- 读取 iostream,直到找到字符串分隔符
- 如何使用STL算法找到字符串中分隔两个不同字母的最短星号序列
- C 错误:无法找到字符串字面运算符
- C 在子字符串内找到字符串的最后一次出现
- 我如何找到字符串的所有安排
- 循环无法在数组中找到字符串
- 如何找到字符串并使用C 文件中的文件删除它
- 如何找到字符串C++中最短的单词
- 找到字符串中的所有回文
- 找到字符串c++中的字符序列并将其擦除
- 如何找到字符串是 Json 或不使用 Jansson
- 如何在不使用循环的情况下简洁地找到字符串中的所有数字
- 如何在不区分大小写的txt文件中找到字符串,并且仍然保留部分大写?在C++中
- 如何在c++中找到字符串中子字符串的出现次数和位置
- 通过重新排列字符找到字符串中的所有回文子字符串