多个字符串:: find

时间:2016-11-03 01:26:41

标签: c++ string find-occurrences

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


}

2 个答案:

答案 0 :(得分:2)

不确定你的意思是什么,但保留你的变量名,这是略微清洁恕我直言。

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

&amp;&amp;运算符将short-circuit并且代码中不会重复字符串。如果您需要更改字符串(虽然它似乎是一个玩具示例而且我对此表示怀疑),您可以在一个地方(DRY principle的一个小应用程序)执行此操作。

答案 1 :(得分:0)

终于做到了,但这是最好的方式吗?

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