多个 string::find

Multiple string::find

有没有像 "if, for loop" 之类的方法来搜索第一个和第二个字符串,如果没有字符串出现则搜索第三个。

我被这三个卡住了。我需要以某种方式检查第一个和第二个字符串中是否有字符串 "aba",但如果没有检查第三个字符串中的 "aba"。一些想法?提前Tnx.

#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 << "\n\n****************************\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){
    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.";
        }
}

不确定您所说的最佳是什么意思,但保留您的变量名称,这 稍微 恕我直言。

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";
   }
}

&& 运算符将 short-circuit and there is no repetition of the strings in the code. Should you need to change the strings (although it appears to be a toy example and I doubt it), you could do it in just one place (a minor application of the DRY principle).