2016-11-03 7 views
0

「if、forループ」などの方法で最初の文字列と2番目の文字列を検索し、3番目の文字列を検索する文字列がない場合。複数の文字列:: find

私はこの3つについています。私は何とか最初と2番目に文字列 "aba"があるかどうかをチェックする必要がありますが、3番目の文字列に "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

紙を取り出します。このタスクを達成するために提案した論理アルゴリズムを、単純で短い論理的な手順で書き留めます。 「最初の文字列を検索します。見つかった場合はこれを行います。それ以外の場合は、次のようにします。等々。 [あなたのラバーダックで論理を書き留めて話し合う](https://en.wikipedia.org/wiki/Rubber_duck_debugging)あなたのラバーダックがそれがうまくいくことに同意すると、書面による論理的プロセスを直接C++に直接変換します。任務完了。 –

+0

あなたが必要とするのは '&&'演算子だけでしょうか? – johnchen902

+0

@ johnchen902問題は、すでにIFループを使用しているので、私は何のループを使うべきではないのですか?私は再び使用できませんか?私はhahahaを失っています... – Beansolder

答えて

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

& &オペレータ意志short-circuitと、コード内の文字列のない繰り返しはありません。文字列を変更する必要がある場合(それはおもちゃの例であると思われますが、疑問ですが)、1か所だけで行うことができます(DRY principleのマイナーアプリケーション)。

+0

Tnx、これはきれいでいいですね。私のものはすべて台無しですが、それは動作します。^_ ^ – Beansolder

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