In: Computer Science
Write a program that takes a string from the user, identifies and counts all unique characters in that given string. You are bound to use only built-in string functions where necessary. For identification of unique characters and for counting of the characters make separate functions.
For character identification
Develop a program that takes a string argument, and returns an array containing all unique characters.
For character counting
Develop a program that takes an array returned from above function as an argument along with the given string and return an array containing the total count of each uniquely identified character present in the argument array.
(Dev Cpp +Multifing )
#include <bits/stdc++.h>
using namespace std;
//function to calculate unique Characters
vector<char> uniqueCharactersFunc(string str){
// map to store and keep track of distinct characters
unordered_map<char, int> mp;
for(int i = 0; i<str.length(); i++){
// iterate the string and store it into map inorder to know the count of each character in the string
mp[str[i]]++;
}
// vector of char typr to return the answer
vector<char>ans;
for(auto it = mp.begin(); it!=mp.end(); it++){
// filling th vector with desired result
ans.push_back(it->first);
}
return ans;
}
// function to calculate unique Characters count
vector<pair<char, int> > countOfUniqueCharactersFunc(vector<char>uniqueCharacters, string str){
//map to iterate and store
unordered_map<char,int>mp;
for(int i = 0; i<str.length(); i++){
mp[str[i]]++;
}
//create vector to store the unique Characters and its count in the given string
vector<pair<char, int> > countOfUniqueCharacters;
for(int i = 0; i<uniqueCharacters.size(); i++){
countOfUniqueCharacters.push_back(make_pair(uniqueCharacters[i], mp[uniqueCharacters[i]]));
}
return countOfUniqueCharacters;
}
int main(){
string inputString;
cin >> inputString;
if(inputString.length() == 0){
cout << "Empty String" << endl;
return 0;
}
// array of unique characters
vector<char> uniqueCharacters = uniqueCharactersFunc(inputString);
// print the unique characters
for(int i=0; i<uniqueCharacters.size(); i++){
cout << uniqueCharacters[i] << " ";
} cout << endl;
// count of unique characters
vector<pair<char, int> > countOfUniqueCharacters = countOfUniqueCharactersFunc(uniqueCharacters, inputString);
// print the count of unique characters
for(int i=0 ; i<countOfUniqueCharacters.size(); i++){
cout << countOfUniqueCharacters[i].first << "->" << countOfUniqueCharacters[i].second << endl;
}
return 0;
}