|
| 1 | + |
| 2 | +using System; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +class VowelCounterClass |
| 6 | +{ |
| 7 | + // Step 1: Declare a delegate |
| 8 | + delegate string VowelsCounterDelegate(string text); |
| 9 | + |
| 10 | + // Step 2: Declare a class field to store user's text |
| 11 | + // so that all methods can access its value |
| 12 | + static string text = ""; |
| 13 | + |
| 14 | + // Program's Entry-Point method |
| 15 | + static void Main() |
| 16 | + { |
| 17 | + // Step-3: instruct user to input any text |
| 18 | + Console.Write("Enter Any Text: "); |
| 19 | + |
| 20 | + // Step-4: store the user's supplied text in field |
| 21 | + text = Console.ReadLine(); |
| 22 | + |
| 23 | + // convert user text to lowercase abc |
| 24 | + // so that we just have to compare with lowercase vowels |
| 25 | + string loweredTxt = text.ToLower(); |
| 26 | + |
| 27 | + // Step-5: Instanstiate the Delegate |
| 28 | + // using the named method 'TextProcessorMethod' |
| 29 | + VowelsCounterDelegate vowelsDelegateMethod = TextProcessorMethod; |
| 30 | + |
| 31 | + // Step-6: execute the delegate like a normal method |
| 32 | + // by sending user's lowered text as its parameter |
| 33 | + string delegateResult = vowelsDelegateMethod(loweredTxt); |
| 34 | + |
| 35 | + // Final Last Step: display the result |
| 36 | + Console.WriteLine(delegateResult); |
| 37 | + } |
| 38 | + |
| 39 | + // named method used to assign value to delegate instance |
| 40 | + static string TextProcessorMethod(string str) |
| 41 | + { |
| 42 | + // Read Code Explanation or Docs for Aggregate's documentation |
| 43 | + return str.Aggregate("", VowelExtractorMethod, VowelsInfoMethod); |
| 44 | + } |
| 45 | + |
| 46 | + // used as first parameter of Aggregate method |
| 47 | + // this method will be called by Aggregate method for every character in text |
| 48 | + static string VowelExtractorMethod(string str, char ch) |
| 49 | + { |
| 50 | + // this will just accumulate (keep adding/concatenating) |
| 51 | + // the vowels's in user's text inside the accumulator |
| 52 | + str += "aeiou".Contains(ch) ? ch : ""; |
| 53 | + return str; |
| 54 | + } |
| 55 | + |
| 56 | + // used as second parameter of Aggregate method |
| 57 | + // this method will be called by Aggregate method |
| 58 | + // only once after all iterations of first parameter method |
| 59 | + // the supplied string parameter will represent the |
| 60 | + // single value of Aggregate method, |
| 61 | + // containing info about vowels in user text |
| 62 | + // number of vowels alongwith the actual vowels present in text |
| 63 | + static string VowelsInfoMethod(string str) |
| 64 | + { |
| 65 | + return $"'{text}' contains {str.Length} Vowels ({str})."; |
| 66 | + } |
| 67 | +} |
| 68 | + |
0 commit comments