In this tutorial, we will write a C# program to find the occurrence of a character in a String.
Program to find occurrence of a character in a string
In this program we are finding the occurrence of each character in a String. To do this we are first creating an array of size 256 (ASCII upper range), the idea here is to store the occurrence count against the ASCII value of that character. For example, the occurrence of ‘A’ would be stored in counter[65] because ASCII value of A is 65, similarly occurrences of other chars are stored in against their ASCII index values.
We are then creating an another array array
to hold the characters of the given String, then we are comparing them with the characters in the String and when a match is found the count of that particular char is displayed using counter
array.
Example:
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 |
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 = "mynameistomhanks"; 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"); } if (cal[i] == 1) { Console.WriteLine("Character " + (char) i); Console.WriteLine("Occurrence = " + cal[i] + " time"); } } } } |
Output: