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.
Asked
Active
Viewed 195 times
0
-
6Replace the photos with the code. – Mihai Alexandru-Ionut Jan 25 '20 at 19:15
-
1hi Kadex, you can reduce the number of lines by checking only for AEIOU for vowels and put else consonants – Clint Jan 25 '20 at 19:18
-
There is a culture-dependent aspect of a character being a "vowel" or a "consonant". I suppose your task is to classify English text, but this should be stated explicitely. – Klaus Gütter Jan 25 '20 at 19:41
-
1Also dupe of [Counting vowel and consonant in a string](https://stackoverflow.com/q/18109890/215552) – Heretic Monkey Jan 25 '20 at 22:08
4 Answers
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