【问题标题】:Multiple string::find多个字符串::find
【发布时间】:2016-11-03 01:26:41
【问题描述】:

有没有像“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.";
}


}

【问题讨论】:

  • 拿出一张纸。用简单、简短、合乎逻辑的步骤写下你提出的完成这项任务的逻辑算法。就像“搜索第一个字符串。如果找到,请执行此操作。否则执行以下操作”。等等。 Discuss your written down logic with your rubber duck。一旦你的橡皮鸭同意它可以工作,只需将写下的逻辑过程直接翻译成 C++。任务完成。
  • 也许您只需要一个&amp;&amp; 运算符?
  • @johnchen902 问题是我不知道要使用什么循环,因为它已经使用了 IF 循环,我不能再使用它了吗?我迷路了哈哈哈……
  • 呃……如果不是循环控制结构可以嵌套。
  • @johnchen902 让它工作了,但是你想改进它还是用这种方式没问题?

标签: c++ string find-occurrences


【解决方案1】:

不确定你所说的最好是什么意思,但保留你的变量名,这是稍微更干净的恕我直言。

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 并且代码中没有重复的字符串。如果您需要更改字符串(尽管这似乎是一个玩具示例,我对此表示怀疑),您可以只在一个地方进行更改(DRY principle 的一个小应用程序)。

【讨论】:

  • Tnx,这看起来干净漂亮。我的一切都搞砸了,但它的工作原理。 ^_^
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多