How to remove odd frequency characters from a string in C++

Hello Learners, today we are going to learn how to remove odd frequency characters from a string in C++. Before learning the session everyone must be clear with the concept of strings.

Strings are defined as a collection of a character that is stored in the form of an array(i.e, character array). The header file used for the string is #include<string.h>.

C++ program: Remove odd frequency characters from a string

The program is very easy, before looking into the program we must know about a few new header files used those are #include<bits/stdc++.h> and #include<string.h> As we discussed above #include<string.h> header file is used for the strings.

#include<bits/stdc++.h> this header file includes all standard libraries. (We do not recommend this as it increases the compiling time) You can use it in coding competitions just to include all libraries at once. That’s all.

To return the length of the string we use “obj.length()” function,” obj” is the string datatype for the variable.

syntax:

        string obj;
       obj.length();

Code:

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
 int main() 
{
    string a;
    int i;
    unordered_map<char, int>char_count; 
    cout<<"enter the sample string to remove the odd frequency character:";
    cin>>a;
    for (i=0;i<a.length();i++) 
    { 
        char_count[a[i]]++; 
    } 
      string after_string = " "; 
    for (i=0;i<a.length();i++) 
    { 
        if (char_count[a[i]]%2!=0) 
            continue; 
        after_string= after_string+a[i]; 
    } 
   cout <<"After removing the odd frequency:"<< after_string << endl; 
   return 0;
}

Output:

enter the sample string to remove the odd frequency character: codespeedy
After removing the odd frequency: dd

Leave a Reply

Your email address will not be published. Required fields are marked *