Is there a code to check if a character is a vowel or consonant? Some thing like char = IsVowel? Or need to hard code?
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’
This works just fine.
public static void Main(string[] args)
{
int vowelsInString = 0;
int consonants = 0;
int lengthOfString;
char[] vowels = new char[5] { 'a', 'e', 'i', 'o', 'u' };
string ourString;
Console.WriteLine("Enter a sentence or a word");
ourString = Console.ReadLine();
ourString = ourString.ToLower();
foreach (char character in ourString)
{
for (int i = 0; i < vowels.Length; i++)
{
if (vowels[i] == character)
{
vowelsInString++;
}
}
}
lengthOfString = ourString.Count(c => !char.IsWhiteSpace(c)); //gets the length of the string without any whitespaces
consonants = lengthOfString - vowelsInString; //Well, you get the idea.
Console.WriteLine();
Console.WriteLine("Vowels in our string: " + vowelsInString);
Console.WriteLine("Consonants in our string " + consonants);
Console.ReadKey();
}
}
Here's a function that works:
public static class CharacterExtentions
{
public static bool IsVowel(this char c)
{
long x = (long)(char.ToUpper(c)) - 64;
if (x*x*x*x*x - 51*x*x*x*x + 914*x*x*x - 6894*x*x + 20205*x - 14175 == 0) return true;
else return false;
}
}
Use it like:
char c = 'a';
if (c.IsVowel()) { // it's a Vowel!!! }
(Yes, it really works, but obviously, this is a joke answer. Don't downvote me. or whatever.)
Try this out:
char[] inputChars = Console.ReadLine().ToCharArray();
int vowels = 0;
int consonants = 0;
foreach (char c in inputChars)
{
if ("aeiou".Contains(c) || "AEIOU".Contains(c))
{
vowels++;
}
else
{
consonants++;
}
}
Console.WriteLine("Vowel count: {0} - Consonant count: {1}", vowels, consonants);
Console.ReadKey();
Console.WriteLine("Please input a word or phrase:");
string userInput = Console.ReadLine().ToLower();
for (int i = 0; i < userInput.Length; i++)
{
//c stores the index of userinput and converts it to string so it is readable and the program wont bomb out.[i]means position of the character.
string c = userInput[i].ToString();
if ("aeiou".Contains(c))
{
vowelcount++;
}
}
Console.WriteLine(vowelcount);
Why not create an array of the vowels/consonants and check if the value is in the array?
You can use the following extension method:
using System;
using System.Linq;
public static class CharExtentions
{
public static bool IsVowel(this char character)
{
return new[] {'a', 'e', 'i', 'o', 'u'}.Contains(char.ToLower(character));
}
}
Use it like:
'c'.IsVowel(); // Returns false
'a'.IsVowel(); // Returns true