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

c++server side programmingprogramming

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

输入

string_one = "tutorialspoint"
string_two = "tutorialsworld"

输出

d n p w

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

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

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

  • 将映射初始化为 map<char, int> chars。

  • 遍历第一个字符串并将每个字符插入到值为 1 的映射中。

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

    • 检查字符是否已经存在。

    • 如果存在,则为其分配 0。

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

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

示例

See the code below.

#include <bits/stdc++.h>
#include <map>
using namespace std;
void findDistinctCharacters(string one, string two){
   // 初始化字符串中的字符存在
   map<char, int> chars;
   // 遍历第一个字符串
   for (int i = 0; i < one.size(); ++i){
      // 将每个字符插入到映射中
      chars.insert({one[i], 1});
   }
   // 遍历第二个字符串
   for (int i = 0; i < two.size(); ++i){
      // 检查当前字符是否在字符串中
      if (chars.count(two[i])) {
         // 为普通字符分配 0
         chars.find(two[i])->second = 0;
      }
      else {
         // 插入新字符
         chars.insert({two[i], 1});
      }
   }
   // 打印不同的字符
   for (auto item: chars){
      // 检查是否存在
      if (item.second == 1) {
         // 打印不同的字符
         cout << item.first << " ";
      }
   }
}
int main(){
   string one = "tutorialspoint";
   string two = "tutorialsworld";
   findDistinctCharacters(one, two);
   return 0;
}

输出

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

d n p w

相关文章