【发布时间】: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++。任务完成。
-
也许您只需要一个
&&运算符? -
@johnchen902 问题是我不知道要使用什么循环,因为它已经使用了 IF 循环,我不能再使用它了吗?我迷路了哈哈哈……
-
呃……如果不是循环,控制结构可以嵌套。
-
@johnchen902 让它工作了,但是你想改进它还是用这种方式没问题?
标签: c++ string find-occurrences