题目:
给出两个字符串数组,a1与a2,创建一个返回的字符串数组r,如果a1的字符串中有a2的子字符串的子字符串,按顺序排列到r中。
例如:a1{“arp”,“live”,“strong”}
a2{“Lively”,“alive”,“harp”,“sharp”,“armstrong”}
return {“arp”,“live”,“strong”}
例2: a1{“tarp”,“mice”,“bull”}
a2{“Lively”,“alive”,“harp”,“sharp”,“armstrong”}
return{};
方法一:
使用find函数,用for auto循环来遍历字符串。
string.find()函数如果没有找到搜索目标,会返回string::npos,所以可以用
if (array2item.find(array1item) != std::string::npos)
来判定a1是否在a2内。
在早期的C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,但是基本没有人去使用它.
C++11中,标准委员会赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得.
例如:
int a = 0;
double b = 3.14;
char c = 'c';
/*---a1为int型---*/
auto a1 = a;
/*---b1为double型---*/
auto b1 = b;
/*---c1为char型---*/
auto c1 = c;
注意:使用auto定义变量时必须对其进行初始化,在编译阶段编译器需要根据初始化表达式来推导auto的实际类型.因此auto并非是一种类型的声明,而是一个类型声明时的占位符,编译器在编译期会将auto替换为变量实际的类型.
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
int main()
{
std::vector<std::string> r;
std::vector<std::string> a1{ "arp", "live", "strong" };
std::vector<std::string> a2{ "Lively","alive","harp","sharp","armstrong" };
for (auto array1item : a1)
{
for (auto array2item : a2) {
if (array2item.find(array1item) != std::string::npos) {
r.push_back(array1item);
break;
}
}
}
sort(r.begin(), r.end());
for (int i = 0; i < r.size(); i++)
{
std::cout << r[i];
}
return 0;
}