0

My program counts vowels and consonants from an entered string of text. Is there a way to make my cases more simplified and look less like a cluster? Just wondering if there is a better way to write them out.

enter image description here

enter image description here

enter image description here

Kadex
  • 69
  • 6

4 Answers4

5

Since you have one method which checks if char is letter, you could check if current char is vowel or consonant using Contains method.

With this method, you can find out the counts for both vowels and consonants using a ternary operator.

if(char.IsLetter(ch)){
   "aeiouAEIOU".Contains(ch) ? vowelCount++ : consonantCount++;
}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
3

Try use regex

var s = "Test, One two three";

Regex r = new Regex("[a-zA-Z]");
MatchCollection m = r.Matches(s);
Regex rv = new Regex("[aeiouAEIOU]");
MatchCollection mv = rv.Matches(s);

var vowels = mv.Count;
var consonants = m.Count - mv.Count;
s-s
  • 382
  • 2
  • 12
1

You might want to punch me in the face but here you go with bitmask

string str = "Test. One two three.";

//               zyxwvutsrqponmlkjihgfedcba      ZYXWVUTSRQPONMLKJIHGFEDCBA
long bitmask = 0b0000010000010000010001000100000000000100000100000100010001;

int vowels = 0, consonants = 0;

foreach (var ch in str)
{
    if(char.IsLetter(ch))
    {
        int shift = ch - 'A';
        if (((bitmask >> shift) & 1) == 1) vowels++;
        else consonants++;
    }
}

Console.WriteLine("Vowels: " + vowels);
Console.WriteLine("Consonants: " + consonants);

or you could use this magic number for bitmask 4575140898685201

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
1

Here is the code snippet which gives you the desired output.

        string text = "This is a Demo Content";
        text = text = Regex.Replace(text, @"[^a-zA-Z]+", "");
        char[] vowels = new char[] { 'a', 'e', 'i', 'o', 'u','A','E','I','O','U' };
        var vowelsCount = text.Count(x => vowels.Contains(x));
        var consonantCount = text.Count(x => !vowels.Contains(x));
TechTrick
  • 11
  • 3
  • Replace the regex to this code: `text = Regex.Replace(text, @"[^a-zA-Z]+", "");`. [0-9] are digits that are not letters and you can replace to empty string in the regex replace no need of second replace – s-s Jan 25 '20 at 22:52