我如何检查一个单词中的所有租船人是否都存在于另一个单词



我正试图制作一个代码,从用户那里获取两个单词,并将它们存储为数组,检查第一个单词的所有字符是否已经存在于第二个单词中,如果是,则只输出是,如果否,则输出否。示例:

输入:

输入第一个单词:

fos

输入第二个单词:

stackoverflow

输出:

YES

我的代码甚至没有接近我真正想要的,但我会把它写下来,也许它会解释我想要做什么。

#include <iostream>
#include <string>
using namespace std;
int main() {

char N1[7];
char N2[10];
cout <<  ("ENTER THE FIRST WORD : ") ;
cin >> N1;
cout <<("ENTER THE SECOND WORD : ");
cin >> N2;
for (int i = 0; i <4; i++)
{
for (int j = 0; j < 7; j++)
{
if (N1[i] = N2[j]) 
{
cout << ("YES") << endl;
}
else
{
cout << ("NO") << endl;
}
}
}
return 0;
}

提前谢谢。

我用简单的搜索和1个布尔变量来跟踪是否找到它。

#include <iostream>
#include <string>
using namespace std;

int main()
{
string s1  = "fosq";
string s2 = "stackoverflow"; 
bool isfound;
for(int i=0;i<s1.length();i++)
{
isfound=false;
for(int j=0;j<s2.length();j++)
{
if(s1[i]==s2[j])
{
isfound=true;
break;
}
} 
if(!isfound)
{
cout<<"Not found";
break;
}
}
if(isfound)
{
cout<<"Yesn";
}
}

在这里,我所做的是在两个字符串上循环,比较每个元素。如果我们找不到任何元素,我就在那里中断搜索,如果我们找到了所有元素,我们就简单地输出Yes。

我不是c++专家,但看起来你想检查所有字符是否都在第二个字符串中,所以你最好在代码中添加布尔值,如下所示:

for (int i = 0; i <4; i++) {
bool charFound = false;
for (int j = 0; j < 7; j++) {
charFound = charFound || (N1[i] == N2[j]); // use OR operator so if found one match it is will stay true
}
if (!charFound) {
cout << ("NO") << endl;
return; // one char is missing - print no and exit
}
}
cout << ("YES") << endl; // if got here you found all char - YES

还要注意代码中的==而不是=(N1[i] == N2[j](,如Azuth的注释中所示

我认为最有效的方法是在计算匹配之前对两个数组进行排序:

#include <iostream>
#include <algorithm>
#include <array>
template <typename T1, typename T2>
bool match(T1& arr1, T2& arr2) {
for (char c2: arr2) {
for (char c1: arr1) {
if (!c1 || !c2) continue;
if (c1 == c2) break;
if (c1 > c2) return false;
}
}
return true;
}
int main() {
std::array<char, 14> arr1 {"stackoverflow"};
std::array<char, 4> arr2 {"fos"};
std::sort(arr1.begin(), arr1.end());
std::sort(arr2.begin(), arr2.end());

if (match(arr1, arr2)) {
std::cout << "YES" << std::endl;
} else {
std::cout << "NO" << std::endl;
}
return 0;
}

最新更新