Find frequency of each word in a string in C#


To find the frequency of each word in a string, you can try to run the following code −

Example

 Live Demo

using System;
class Demo {
   static int maxCHARS = 256;
   static void calculate(String s, int[] cal) {
      for (int i = 0; i < s.Length; i++)
      cal[s[i]]++;
   }

   public static void Main() {
      String s = "Football!";
      int []cal = new int[maxCHARS];
      calculate(s, cal);
      for (int i = 0; i < maxCHARS; i++)
      if(cal[i] > 1) {
         Console.WriteLine("Character "+(char)i);
         Console.WriteLine("Occurrence = " + cal[i] + " times");
      }
   }
}

Output

Character l
Occurrence = 2 times
Character o
Occurrence = 2 times

Above, we have set a string and an integer array. This helps us in getting the repeated values. The method calculates −

static void calculate(String s, int[] cal) {
   for (int i = 0; i < s.Length; i++)
   cal[s[i]]++;
}

The value are then printed that shows the duplicate elements as well −

for (int i = 0; i < maxCHARS; i++)
if(cal[i] > 1) {
   Console.WriteLine("Character "+(char)i);
   Console.WriteLine("Occurrence = " + cal[i] + " times");
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements