多个字符串:找到

Multiple string::find

本文关键字:找到 字符串      更新时间:2023-10-16

是否有类似"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.";
        }
}