C++程序中查找两个字符串的不常见字符


在本教程中,我们将学习如何从给定的两个字符串中查找不同的字符。让我们来看一个例子。

输入

string_one = "tutorialspoint"
string_two = "tutorialsworld"

输出

d n p w

我们将使用哈希表来解决这个问题。它比编写两个嵌套循环更有效率。

让我们看看解决程序的步骤。

  • 用一些随机值初始化两个字符串。

  • 初始化一个map为map<char, int> chars。

  • 遍历第一个字符串并将每个字符插入map中,值为1。

  • 现在,遍历第二个字符串。

    • 检查字符是否已存在。

    • 如果存在,则将其赋值为0。

    • 如果不存在,则插入该字符,值为1。

  • 遍历map并打印值为1的字符。

示例

请看下面的代码。

在线演示

#include <bits/stdc++.h>
#include <map>
using namespace std;
void findDistinctCharacters(string one, string two){
   // initializing char presence in string
   map<char, int> chars;
   // iterating over the first string
   for (int i = 0; i < one.size(); ++i){
      // inserting every character into map
      chars.insert({one[i], 1});
   }
   // iterating over the second string
   for (int i = 0; i < two.size(); ++i){
      // checking whether the current char in string or not
      if (chars.count(two[i])) {
         // assigning 0 for common chars
         chars.find(two[i])->second = 0;
      }
      else {
         // insering new chars
         chars.insert({two[i], 1});
      }
   }
   // printing the distinct characters
   for (auto item: chars){
      // checking the presence
      if (item.second == 1) {
         // printing the distinct char
         cout << item.first << " ";
      }
   }
}
int main(){
   string one = "tutorialspoint";
   string two = "tutorialsworld";
   findDistinctCharacters(one, two);
   return 0;
}

输出

如果运行上述代码,您将得到以下结果。

d n p w

结论

如果您在本教程中有任何疑问,请在评论部分提出。

更新于:2020年12月29日

473 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.