Print number of words, vowels and frequency of each character

Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line.
Example :Â
Input : How Good GOD Is. Output : Number of words = 4 Number of vowels = 5 Number of upper case characters = 6 Character = Frequency = 3 Character = . Frequency = 1 Character = D Frequency = 1 Character = G Frequency = 2 Character = H Frequency = 1 Character = I Frequency = 1 Character = O Frequency = 1 Character = d Frequency = 1 Character = o Frequency = 3 Character = s Frequency = 1 Character = w Frequency = 1
Approach : We use a TreeMap to store characters and their frequencies. TreeMap is used to get the output in sorted order.
Below is Java implementation of above approach :Â
C++
// C++ program to print Number of Words,// Vowels and Frequency of Each Character#include <bits/stdc++.h>using namespace std;Â
void words(string str){    int wcount = 0, ucount = 0, vcount = 0;    for (int i = 0; i < str.length(); i++)    {        char c = str[i];        switch (c)        {            case ' ':            case '.':            wcount++; // more delimiters can be given        }Â
        switch (c)        {            case 'A':            case 'E':            case 'I':            case 'O':            case 'U':            case 'a':            case 'e':            case 'i':            case 'o':            case 'u':                vcount++;        }Â
        if (c >= 65 and c <= 90) ucount++;    }Â
    cout << "Number of words = "         << wcount << endl;    cout << "Number of vowels = "         << vcount << endl;    cout << "Number of upper case characters = "         << ucount << endl;}Â
// Function to calculate the frequency// of each character in the stringvoid frequency(string str){    // Creates an empty TreeMap    map<char, int> hmap;Â
    // Traverse through the given array    for (int i = 0; i < str.length(); i++)        hmap[str[i]]++;Â
    // Print result    for (auto i : hmap)    {        cout << "Character = " << i.first;        cout << " Frequency = "             << i.second << endl;    }}Â
// Driver Codeint main(int argc, char const *argv[]){Â Â Â Â string str = "Geeks for Geeks.";Â Â Â Â words(str);Â Â Â Â frequency(str);Â Â Â Â return 0;}Â
// This code is contributed by// sanjeev2552 |
Java
// Java program to print Number of Words,// Vowels and Frequency of Each Characterimport java.util.*;import java.lang.*;import java.io.*;Â
public class Stringfun{Â Â Â Â String str = "Geeks for Geeks.";Â
    void words()    {        int wCount = 0, uCount = 0, vCount = 0;Â
        for (int i = 0; i < str.length(); i++)        {            char c = str.charAt(i);Â
            switch (c)            {            case ' ':            case '.':                wCount++; // more delimiters can be given            }Â
            switch (c)            {            // program for calculating number of vowels            case 'A':            case 'E':            case 'I':            case 'O':            case 'U':            case 'a':            case 'e':            case 'i':            case 'o':            case 'u':                vCount++;            }Â
            if (c >= 65 && c <= 90)            {                uCount++;            }        }Â
        System.out.println("Number of words = " + wCount);        System.out.println("Number of vowels = " + vCount);        System.out.println("Number of upper case characters = "                                                        + uCount);    }Â
    // Function to calculate the frequency    // of each character in the string    void frequency()    {        // Creates an empty TreeMap        TreeMap<Character, Integer> hmap =                     new TreeMap<Character, Integer>();          // Traverse through the given array        for (int i = 0; i < str.length(); i++)        {            Integer c = hmap.get(str.charAt(i));              // If this is first occurrence of element            if (hmap.get(str.charAt(i)) == null)               hmap.put(str.charAt(i), 1);              // If elements already exists in hash map            else              hmap.put(str.charAt(i), ++c);        }                 // Print result        for (Map.Entry m:hmap.entrySet())          System.out.println("Character = " + m.getKey() +                         " Frequency = " + m.getValue());    }Â
    // Driver program to run and test above program    public static void main(String args[]) throws IOException    {        Stringfun obj = new Stringfun();        obj.words();        obj.frequency();    }} |
Python 3
# Python3 program to print Number of Words,# Vowels and Frequency of Each CharacterÂ
# A method to count the number of# uppercase character, vowels and number of wordsdef words(str):    wcount = vcount = ucount = i = 0    while i < len(str):        ch = str[i]                 # condition checking for word count        if (ch == " " or ch == "."):            wcount += 1                     # condition checking for vowels        # in lower case            if(ch == "a" or ch == "e" or           ch == "i" or ch == 'o' or ch == "u"):            vcount += 1                     # condition checking for vowels in uppercase        if (ch == "A" or ch == "E" or            ch == "I" or ch == 'O' or ch == "U"):            vcount += 1                     # condition checking for upper case characters        if (ord(ch) >= 65 and ord(ch) <= 90):            ucount += 1        i += 1             print("number of words = ", wcount)    print("number of vowels = ", vcount)    print("number of upper case characters = ",                                        ucount)     # a method to print the frequency# of each character.def frequency(str):    i = 1         # checking each and every    # ascii code character    while i < 127:        ch1 = chr(i)        c = 0        j = 0        while j < len(str):            ch2 = str[j]            if(ch1 == ch2):                c += 1            j += 1                     # condition to print the frequency        if c > 0:            print("Character:", ch1 +                  " Frequency:", c)        i += 1         # Driver CodeÂ
# sample string to check the code    s = "Geeks for Geeks."Â
# function callingwords(s)frequency(s)Â
# This code is contributed by Animesh_Gupta |
C#
using System;using System.Collections.Generic;Â
public static class GFG{       // C# program to print Number of Words,    // Vowels and Frequency of Each Character    public static void words(string str)    {        int wcount = 0;        int ucount = 0;        int vcount = 0;        for (int i = 0; i < str.Length; i++) {            char c = str[i];            switch (c) {            case ' ':            case '.':                wcount++; // more delimiters can be given                break;            }Â
            switch (c) {            case 'A':            case 'E':            case 'I':            case 'O':            case 'U':            case 'a':            case 'e':            case 'i':            case 'o':            case 'u':                vcount++;                break;            }Â
            if (c >= 65 && c <= 90) {                ucount++;            }        }Â
        Console.Write("Number of words = ");        Console.Write(wcount);        Console.Write("\n");        Console.Write("Number of vowels = ");        Console.Write(vcount);        Console.Write("\n");        Console.Write("Number of upper case characters = ");        Console.Write(ucount);        Console.Write("\n");    }Â
    // Function to calculate the frequency    // of each character in the string    public static void frequency(string str)    {        // Creates an empty TreeMap        Dictionary<char, int> hmap            = new Dictionary<char, int>();Â
        // Traverse through the given array        for (int i = 0; i < str.Length; i++) {            if (hmap.ContainsKey(str[i])) {                hmap[str[i]] = hmap[str[i]] + 1;            }            else {                hmap.Add(str[i], 1);            }        }Â
        // Print result        foreach(var i in hmap)        {            Console.Write("Character = ");            Console.Write(i.Key);            Console.Write(" Frequency = ");            Console.Write(i.Value);            Console.Write("\n");        }    }Â
    // Driver Code    public static void Main(string[] args)    {        string str = "Geeks for Geeks.";        words(str);        frequency(str);    }Â
    // This code is contributed by Aarti_Rathi} |
Javascript
<script>Â
// JavaScript program to print Number of Words,// Vowels and Frequency of Each CharacterÂ
// A method to count the number of// uppercase character, vowels and number of wordsfunction words(str){    let wcount = 0,vcount = 0,ucount =0,i = 0    while(i < str.length){        let ch = str[i]                 // condition checking for word count        if (ch == " " || ch == ".")            wcount += 1                     // condition checking for vowels        // in lower case            if(ch == "a" || ch == "e" ||           ch == "i" || ch == 'o' || ch == "u")            vcount += 1                     // condition checking for vowels in uppercase        if (ch == "A" || ch == "E" ||            ch == "I" || ch == 'O' || ch == "U")            vcount += 1Â
        // condition checking for upper case characters        if (ch.charCodeAt(0) >= 65 && ch.charCodeAt(0) <= 90){            ucount += 1        }        i += 1    }             document.write("number of words = ", wcount,"</br>")    document.write("number of vowels = ", vcount,"</br>")    document.write("number of upper case characters = ",                                        ucount,"</br>")}     // a method to print the frequency// of each character.function frequency(str){         let i = 1         // checking each and every    // ascii code character    while(i < 127){        let ch1 = String.fromCharCode(i);        let c = 0        let j = 0        while(j < str.length){            let ch2 = str[j]            if(ch1 == ch2)                c += 1            j += 1        }                     // condition to print the frequency        if(c > 0)            document.write("Character:", ch1 + " Frequency:", c,"</br>")        i += 1    }}         // Driver CodeÂ
// sample string to check the code    let s = "Geeks for Geeks."Â
// function callingwords(s)frequency(s)Â
// This code is contributed by shinjanpatraÂ
</script> |
Output
Number of words = 3 Number of vowels = 5 Number of upper case characters = 2 Character = Frequency = 2 Character = . Frequency = 1 Character = G Frequency = 2 Character = e Frequency = 4 Character = f Frequency = 1 Character = k Frequency = 2 Character = o Frequency = 1 Character = r Frequency = 1 Character = s Frequency = 2
Time Complexity : O(n), where n is the number of characters in the string.Â
Auxiliary Space : O(1).



