Print each word in a sentence with their corresponding average of ASCII values - GeeksforGeeks

18 May, 2021
Given a sentence, the task is to find the average of ASCII values of each word in the sentence and print it with the word.Examples:  
Input: sentence = "Learning a string algorithm"
Output: 
Learning - 102
a - 97
string - 110
algorithm - 107
Approach: 
Take an empty string and start traversing the sentence letter by letter.Add letter to the string and add its ASCII value to the sum.If there is an empty space calculate the average by dividing the sum by the length of the string (word)Clear the string so that it can be used for the next wordAlso set the sum to zero.
Take an empty string and start traversing the sentence letter by letter.
Add letter to the string and add its ASCII value to the sum.
If there is an empty space calculate the average by dividing the sum by the length of the string (word)
Clear the string so that it can be used for the next word
Also set the sum to zero.
Below is the implementation of the above approach: 
C++
Java
Python 3
C#
Javascript
// C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the// average of each word in a sentencevoid calculateAverage(string sentence){    // Word initialised to an empty string    string word = "";     // Sum of ascii values    int sum = 0;     int len = sentence.length();     for (int i = 0; i < len; ++i) {         // If character is a space        if (sentence[i] == ' ') {             // Calculate the average            int average = sum / word.length();             cout << word << " - "                 << average << endl;             // Clear the word and            // set the sum to 0            word.clear();            sum = 0;        }         else {             // Add the ascii value to sum and            // also add the letter to the word            sum += sentence[i];            word += sentence[i];        }    }     // Calculate the average of last word    int average = sum / word.length();     cout << word << " - " << average;} // Driver codeint main(){     // Get the sentence    string sentence            = "Learning a string algorithm";     // Calculate the average    calculateAverage(sentence);     return 0;}
// Java program of the above approachimport java.util.*;public class Solution{// Function to calculate the// average of each word in a sentencestatic void calculateAverage(String sentence){    // Word initialised to an empty string    String word = "";     // Sum of ascii values    int sum = 0;     int len = sentence.length();     for (int i = 0; i < len; ++i) {         // If character is a space        if (sentence.charAt(i) == ' ') {             // Calculate the average            int average = sum / word.length();             System.out.println( word + " - "+ average );             // Clear the word and            // set the sum to 0            word="";            sum = 0;        }         else {             // Add the ascii value to sum and            // also add the letter to the word            sum += sentence.charAt(i);            word += sentence.charAt(i);        }    }     // Calculate the average of last word    int average = sum / word.length(); System.out.print( word + " - " + average);} // Driver codepublic static void main(String[] args){     // Get the sentence    String sentence            = "Learning a string algorithm";     // Calculate the average    calculateAverage(sentence); }}//contributed by Arnab Kundu
# Python 3 program of the above approach # Function to calculate the# average of each word in a sentencedef calculateAverage(sentence):     # Word initialised to    # an empty string    word = ""     # Sum of ascii values    sum = 0     l = len(sentence)     for i in range(l):         # If character is a space        if (sentence[i] == ' ') :             # Calculate the average            average = sum // len(word)             print(word , " - ", average)             # Clear the word and            # set the sum to 0            word = ""            sum = 0         else :             # Add the ascii value to sum and            # also add the letter to the word            sum += ord(sentence[i])            word += sentence[i]     # Calculate the average of last word    average = sum // len(word)     print(word , " - " , average) # Driver codeif __name__ == "__main__":     # Get the sentence    sentence = "Learning a string algorithm"     # Calculate the average    calculateAverage(sentence) # This code is contributed# by ChitraNayal
// C# implementation of above approachusing System; class GFG{// Function to calculate the// average of each word in a sentencestatic void calculateAverage(String sentence){    // Word initialised to an empty string    String word = "";     // Sum of ascii values    int sum = 0;     int len = sentence.Length;    int average = 0;    for (int i = 0; i < len; ++i)    {                 // If character is a space        if (sentence[i] == ' ')        {             // Calculate the average            average = sum / word.Length;             Console.WriteLine(word + " - " + average);             // Clear the word and            // set the sum to 0            word="";            sum = 0;        }         else        {             // Add the ascii value to sum and            // also add the letter to the word            sum += sentence[i];            word += sentence[i];        }    }     // Calculate the average of last word    average = sum / word.Length;     Console.Write(word + " - " + average);} // Driver codepublic static void Main(){    // Get the sentence    String sentence = "Learning a string algorithm";     // Calculate the average    calculateAverage(sentence);}} // This code is contributed// by PrinciRaj1992
<script>      // JavaScript implementation of above approach      // Function to calculate the      // average of each word in a sentence      function calculateAverage(sentence) {        // Word initialised to an empty string        var word = "";         // Sum of ascii values        var sum = 0;         var len = sentence.length;        var average = 0;        for (var i = 0; i < len; ++i) {          // If character is a space          if (sentence[i] === " ") {            // Calculate the average            average = parseInt(sum / word.length);             document.write(word + " - " + average + "<br>");             // Clear the word and            // set the sum to 0            word = "";            sum = 0;          } else {            // Add the ascii value to sum and            // also add the letter to the word             sum += sentence[i].charCodeAt(0);            word += sentence[i];          }        }         // Calculate the average of last word        average = parseInt(sum / word.length);        document.write(word + " - " + average + "<br>");      }       // Driver code      // Get the sentence      var sentence = "Learning a string algorithm";       // Calculate the average      calculateAverage(sentence);    </script>
Learning - 102
a - 97
string - 110
algorithm - 107
 
Time Complexity: O(N) 
andrew1234
princiraj1992
ukasp
rdtank
ASCII
Technical Scripter 2018
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Hill Cipher
Minimum changes to a string to make all substrings distinct
How to Append a Character to a String in C
Convert character array to string in C++
Converting Roman Numerals to Decimal lying between 1 to 3999
sprintf() in C
Print all subsequences of a string