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
結論
如果您在本教程中有任何疑問,請在評論部分提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP