In this program will shown you how to find the frequency of characters in a string using C# Console App.
This program in C# language counts the number of occurrences in a text file of all the searched characters.
Example:
Text file contains the text “I am a programmer”.
The searched characters: a, b, c, d, e.
The number of occurrences:
- a:3
- b:3
- c:1
- d:1
- e:5
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
class Program { static void search_chars(string characters, int size) { int[] repetition= new int[size]; //initialize to 0 for (int i = 0; i < size; i++) repetition[i] = 0; string path = @"d:\calisma\file.txt"; using (StreamReader sr = new StreamReader(path)) { char[] c = null; while (sr.Peek() >= 0) { c= new char[1]; sr.Read(c, 0 , 1); // The character read is compare with // all characters searched for (int i = 0; i < size; i++) { // if he is equal he is incrementing // the counter associated with the character if (c[0] == characters[i]) repetition[i]++; } } } for (int i = 0; i < size; i++) Console.WriteLine("\t {0}:{1}", characters[i], repetition[i]); } static void Main(string[] args) { string str = "abcdelo"; search_chars(str, str.Length); Console.ReadLine(); } } |
Output: