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

How can i check if all charterers in a word are existing into the other one?

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

输入:

输入第一个单词:

fos

输入第二个单词:

Whosebug

输出:

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

提前致谢。

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

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]) 中的 == 而不是 =,如 Aziuth 的评论

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

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



int main()
{
string s1  = "fosq";
string s2 = "Whosebug"; 
  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<<"Yes\n";
  }
}

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

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

#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 {"Whosebug"};
    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;
}