【发布时间】:2020-03-28 10:45:16
【问题描述】:
我有两个字符串向量 a 和 b 与 a[0]="hello",a[1]="world",b[0]="heyyy" 和 b[1]="namaste" 我必须确定以下 a[0] and b[0] 是否有任何匹配和 a[1] and b[1]任何匹配的东西。如果a[0] and b[0] 有一个或多个字符匹配,则打印"YES",否则打印"NO"。同样,如果a[1] and b[1] 有一个或多个字符匹配,则打印"YES",否则打印"NO"。例如从上面的信息来看,a[0] and b[0] 有'h' and 'e' 匹配,a[1] and b[1] 没有字符匹配。最后,预期的输出是
"YES"
"NO"
基于以上信息,作为 C++ 的初学者,我开发了一个 C++ 程序,它甚至不是部分正确的。如果有人解决这个问题,那就太好了。提前致谢。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
std::vector<string>a,b;
a={"hello", "world"};
b={"heyyy", "namaste"};
const char* acstr;
const char* bcstr;
acstr = a[0].c_str();
bcstr = b[0].c_str();
for(int i=0;i<sizeof(acstr);i++)
{
for(int j=0;j<sizeof(bcstr);j++)
{
if(acstr[i]==bcstr[j])
{
cout << "YES";
}
else{
continue;
}
}
}
return 0;
}
【问题讨论】:
-
我会编写一个函数,对两个
strings 进行比较并返回一个bool。一旦可行,那么我会担心遍历向量。 -
为了您的比较,您是否要查看两个字符串
a和b是否有任何等效的子字符串? (例如,s = "axxx"和b = "yyyya"将返回true,因为它们都包含a)或者您是否只检查a[i] == b[i]是否为 [0,min(a.size(), b.size())中的任何i? -
你为什么要把
std::string和const char*混在一起?std::string可以做所有const char*可以(以及更多)的事情