Change gender of a given string

Given a string, write a function that will toggle all the gender specific words in the input string

Example

INPUT
s = "She is my daughter"

OUTPUT
"He is my son"

Time Complexity : O(), where n is the length of the string

Algorithm

1. Create a hash map which maps all the female words to male words and viceversa

2. Traverse the string, for every word
    a. check if the word is gender specific word or not, if it is a gender specific word replace the     word with the mapped word(counterpart word)
    b. Print the new sentence

C++ Program

#include <bits/stdc++.h>
#include <unordered_map>

using namespace std;

// A Funtion that returns the new string with gender
// changed
string genderChange(string s)
{
    //Some of the gender words 
    unordered_multimap <string, string> dict =
    {
      {"boy", "girl"}, {"girl", "boy"},
      {"father", "mother"}, {"mother", "father"},
      {"husband", "wife"}, {"wife", "husband"},
      {"he", "she"}, {"she", "he"},
      {"male", "female"}, {"female", "male"},
      {"man", "woman"}, {"woman", "man"},
      {"Mr", "Ms"}, {"Mr", "Ms"},
      {"sir", "madam"}, {"madam", "sir"},
      {"son", "daughter"}, {"daughter", "son"},
      {"uncle", "aunt"}, {"aunt", "uncle"},
    };
 
    s = s + ' '; // Append a space at the end
 
    int n = s.length();
 
    // 'temp' string will hold the intermediate words
    // and 'res' string will be our result
    string temp = "", res = "";
 
    for (int i=0; i<=n-1; i++)
    {
        if (s[i] != ' ')
            temp.push_back(s[i]);
        else
        {
            // If this is a 'male' or a 'female' word then
            // swap this with its counterpart
            if (dict.find(temp) != dict.end())
                temp = dict.find(temp)->second;
 
            res = res + temp + ' ';
            temp.clear();
        }
    }
 
    return(res);
}
 

int main()
{
    string s = "She is my daughter";
 
    cout << genderChange(s)<<endl;  
 
    return (0);
}
Try It

 


Next > < Prev
Scroll to Top