Question
Take input of 1 character from user. It can be the vowel or consonant.
After the user gives input so it will ask do you want to input the character again for Yes press Y and for No press N.
When the user says No, you have to show how much vowel and how much consonant use has input.
Please do this question using For loop. I think array must be use. I did this code it counting vowel and consonant and spacing. But I cant take the input multiple times.
My code doesnn't run multiple times. I can only write sentence or a character in a line so it will only count that. But I want to ask the user to enter a character again.
I want my code to run multiple times so the user can give input multiple times as I explain my question.
using System;
public class vowelConsonant
{
public static void Main()
{
int vowels = 0;
int consonant = 0;
int space = 0;
Console.WriteLine("Enter a Sentence or a Character");
string v = Console.ReadLine().ToLower();
for (int i = 0; i < v.Length; i++)
{
if (v[i] == 'a' || v[i] == 'e' || v[i] == 'i' || v[i] == 'o' || v[i] == 'u')
{
vowels++;
}
else if (char.IsWhiteSpace(v[i]))
{
space++;
}
else
{
consonant++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", vowels);
Console.WriteLine("Your total number of constant is: {0}", consonant);
Console.WriteLine("Your total number of space is: {0}", space);
Console.ReadLine();
}
}
Thanks
Just put an infinite loop around the whole thing.
using System;
public class vowelConsonant
{
public static void Main()
{
// Infinite loop.
while (true)
{
int vowels = 0;
int consonant = 0;
int space = 0;
Console.WriteLine("Enter a Sentence or a Character");
string v = Console.ReadLine().ToLower();
for (int i = 0; i < v.Length; i++)
{
if (v[i] == 'a' || v[i] == 'e' || v[i] == 'i' || v[i] == 'o' || v[i] == 'u')
{
vowels++;
}
else if (char.IsWhiteSpace(v[i]))
{
space++;
}
else
{
consonant++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", vowels);
Console.WriteLine("Your total number of constant is: {0}", consonant);
Console.WriteLine("Your total number of space is: {0}", space);
}
}
}
This application to count vowels and consonants letters in a sentence.
This is another solution with less line of codes with understanding idea of using loop and nested loop with char arrays.
Application interface with controls names
namespace Program8_4
{
public partial class Form1 : Form
{
// declare the counter variables in field
int iNumberOfVowels = 0;
int iNumberOfConsonants = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// call the methods in this event
GetVowels(txtStringInput.Text);
GetConsonants(txtStringInput.Text);
// show the result in a label
lblOutput.Text = "The number of vowels : " + iNumberOfVowels.ToString() + Environment.NewLine+
"The number of consonants : " + iNumberOfConsonants.ToString();
// assign zero the counters to not add the previous number to new number, and start counting from zero again
iNumberOfVowels = 0;
iNumberOfConsonants = 0;
}
private int GetConsonants(string strFindConsonants)
{
// Declare char array to contain consonants letters
char[] chrConsonants = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X',
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };
// loop to get each letter from sentence
foreach (char Consonants in strFindConsonants)
{
// another nested loop to compare each letter with all letters contains in chrConsonants array
for (int index = 0; index < chrConsonants.Length; index++)
{
// compare each letter with each element in charConsonants array
if (Consonants == chrConsonants[index])
{
// If it is true add one to the counter iNumberOfConsonants
iNumberOfConsonants++;
}
}
}
// return the value of iNumberOfConsonants
return iNumberOfConsonants;
}
private int GetVowels(string strFindVowels)
{
// Declare char array to contain vowels letters
char[] chrVowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O','U' };
// loop to get each letter from sentence
foreach (char Vowels in strFindVowels)
{
// another nested loop to compare each letter with all letters contains in chrVowels array
for (int index = 0; index < chrVowels.Length; index++)
{
// compare each letter with each element in chrVowels array
if (Vowels == chrVowels[index])
{
// If it is true add one to the counter iNumberOfVowels
iNumberOfVowels = iNumberOfVowels+1;
}
}
}
// return the value of iNumberOfVowels
return iNumberOfVowels;
}
}
}
We can simply find the required vowels and consonant counts using Regex.Matches() function.
Below is the working code snippet:
public static void Main()
{
Console.WriteLine("Enter a Sentence or a Character");
string input = Console.ReadLine().ToLower();
string vowels = #"[aeiouAEIOU]+"; //regular expression to match vowels
string consonants = #"[^aeiouAEIOU]+"; //regular expression to match consonants
string space = #"[\S]+";
int vowLength = new Regex(vowels).Matches(input).Count;
int conLength = new Regex(consonants).Matches(input).Count;;
int spLength = new Regex(space).Matches(input).Count;;
Console.WriteLine("Your total number of vowels is: {0}", vowLength);
Console.WriteLine("Your total number of constant is: {0}", conLength);
Console.WriteLine("Your total number of space is: {0}", spLength);
}
Related
im trying to split a string into a chars(which i have semi done) and use each char to compare it to my dictionary full of random strings, and then add that chars value in the dictionary to a finished string. the problem is what its outputting- the chars are not in order.
ex: USER INPUT: "hello"---
ex: CONSOLE: "e"-"l"-"l"-"o"-"h"
thats what happens mostly. any answer as to how i can get it to spell it correctly in the console?
Code:
private void complete_text_Click(object sender, RoutedEventArgs e)
{
end_result = input_box.Text.ToString();
string end_translated_result = "";
for (int i = 0; i < ZENOX_LANGUAGE.Keys.Count; i ++)
{
foreach (char iq in end_result.ToCharArray())
{
if (iq.ToString().ToLower() == ZENOX_LANGUAGE.Keys.ElementAt(i).ToString().ToLower())
{
Console.WriteLine(iq);
end_translated_result += ZENOX_LANGUAGE.Values.ElementAt(i) + " ";
//Console.WriteLine("sender: " + sender.ToString() + " c: " + end_result[iq].ToString().ToLower() + " s:" + ZENOX_LANGUAGE.Keys.ElementAt(i));
Console.WriteLine("end translated result: " + end_result);
}
}
}
}
As it stands, the order of keys in your dictionary will influence the order that output appears, because you're doing:
foreach(var k in dictionary.Keys)
foreach(char c in someString)
if(c == k)
Console.Write(c)
And dictionary keys have no defined order.
Swapping the loops over will mean (as long as the dictionary has the key you're looking for, as it's a condition that leads to printing the char) that the output will appear in order of chars in the string..
..but I can't actually work out why you enumerate the keys and then run a loop looking for the character. I'd just loop over the string and use the char to index the dictionary if I was building some sort of translator map:
var map = new Dictionary<char, char>() {
{ 'h', 'Z' },
{ 'e', 'Y' },
{ 'l', 'X' },
{ 'o', 'W' }
};
var toTrans = "hello";
foreach(char c in toTrans)
Console.Write(map[c]);
This will print "ZYXXW" for an input of "hello";
If you're mapping chars to strings, with case insensitivity it's as simple as:
var map = new Dictionary<char, string>() {
{ 'h', "Z0" },
{ 'e', "Y0" },
{ 'l', "X0" },
{ 'o', "W0" }
};
var toTrans = "HelLO";
foreach(char c in toTrans)
Console.Write(map[Char.ToLower(c)]);
This will print "Z0Y0X0X0W0"
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 2 years ago.
I'm quite new to C# and I made this method to create random words and it takes in a minimum length and maximum as a parameter. But when I put it in a for loop 20 times I can see that every few in a row are identical. How do I fix this?
static string makename(int min, int max)
{
Random rnd = new Random();
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char[] consonants = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' };
int namelength = rnd.Next(min, max);
char twoago = '2';
char oneago = '1';
string name = "";
for (int i = 0; i < namelength; i++)
{
if (oneago != twoago)
{
twoago = oneago;
if (rnd.Next(0, 2) == 1)
{
name = name + vowels[rnd.Next(0, vowels.Count())];
oneago = 'v';
}
else
{
name = name + consonants[rnd.Next(0, consonants.Count())];
oneago = 'c';
}
}
else if (oneago == 'c')
{
name = name + vowels[rnd.Next(0, vowels.Count())];
oneago = 'v';
}
else
{
name = name + consonants[rnd.Next(0, consonants.Count())];
oneago = 'c';
}
if (i == 0)
{
name = name.ToUpper();
}
}
return name;
}
Here is an example of the output (parameters are 4,10) (there was one output before this I cut off):console
When you instantiate the Random (with new Random();) random is being reset to the system clock. Your method is getting called quickly enough that the call is sometimes getting the same system clock time. Random on a computer is never random. It is based on a fairly random mathematical function that behaves fairly randomly as long as it is seeded (started) with a different number each time.
Note, you only need to seed random once for an application run in order for it to behave randomly. It is when you seed it multiple times that you get into trouble.
I am currently writing a Caesar Cipher program in C# for my assignment and I am having a problem.
I am approaching this task using an array where I store the whole alphabet and I declare a shift variable which is defined by character index in the array - the iteration of a for loop. The shift calculation is done in a foreach loop, that fetches a character from a string that is read from a text file. Foreach loop is contained within a for loop that iterates to output every possible shift.
However, the problem is that when I try to access the character in an array by a value of my shift variable, the program doesn't seem to access the character I want, it just outputs the same character as in the original string.
This is the code for the program:
using System;
using System.IO;
public class caesar_shift
{
public static void Main()
{
string file = #"C:\Users\terasss2\Desktop\Programming and Data Structures\caesarShiftEncodedText.txt"; //String variable that stores a file location
string encrypted_text = File.ReadAllText(file); //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
char[] alphabet = new char[26]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for(int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
foreach(char c in encrypted_text)
{
character = c;
if(character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if(shift <= 0)
shift = shift + 26;
if(shift >= 26)
shift = shift - 26;
character = alphabet[shift]; //Set the character to a shifted letter by accessing the array element of a value shift
Console.WriteLine(character);
decoded_text = decoded_text + character;
}
Console.WriteLine("\nShift {0} \n {1}",i + 1, decoded_text);
}
}
}
I played a bit with your code. The following gives you the solution, but you have to take care: you couldonly use capital letters, because theres a difference in upper and lower charts. I used the ToUpper() method. Works fine for me. I think that's what your problem was.
public static void Main()
{
string encrypted_text = "BCD"; //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
encrypted_text = encrypted_text.ToUpper();
char[] alphabet = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for (int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
decoded_text = "";
foreach (char c in encrypted_text)
{
character = c;
if (character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if (shift <= 0)
shift = shift + 26;
if (shift >= 26)
shift = shift - 26;
decoded_text += alphabet[shift];
}
Console.WriteLine("\nShift {0} \n {1}", i + 1, decoded_text);
}
}
I took a look at your code and made a slight adjustment. First of all, I converted it to a method that lets you pass in the string and the amount you want to shift, so that you can either call it in a loop from 0 to 25 to see all the permutations, or you can just get a single value. I also check to see if each character is actually in the array, and if it isn't, then don't change it (in your code you were only checking for '\' and ' ' characters:
public static string ShiftText(string input, int shiftAmount)
{
if (input == null) return null;
char[] alphabet =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
shiftAmount %= 26; // Ensure shift is between 0 and 25
var shiftedText = string.Empty;
foreach (var character in input)
{
var index = Array.IndexOf(alphabet, character);
if (index < 0)
{
// This character isn't in the array, so don't change it
shiftedText += character;
}
else
{
var newIndex = index - shiftAmount;
// If it's negative, wrap around to end of array
if (newIndex < 0) newIndex += 26;
shiftedText += alphabet[newIndex];
}
}
return shiftedText;
}
But another way to do this that works for upper AND lower case, and which is less code, is to simply test if char.IsLetter(character), and then shift the ASCII value of the character within the same 0-25 range.
For example, this does the same as the code above, only it works for lower case letters as well. The difference here is that before we compare the character to our lowest valued character ('a' or 'A'), we test if char.IsLower() first. This way we stay within the ASCII range for this character set:
/// <summary>
/// This method takes the input string and shifts all letter characters
/// to the left (subtracts) by the amount specified in shiftAmount, so
/// if shiftAmount = 1, then 'M' becomes 'L', and 'a' becomes 'z'.
/// </summary>
/// <param name="input">The input string to apply changes to</param>
/// <param name="shiftAmount">A value from 0 to 25, used to shift the characters</param>
/// <returns>The modified (shifted) string</returns>
public static string ShiftText(string input, int shiftAmount)
{
if (input == null) return null;
// Ensure shift is between 0 and 25
shiftAmount %= 26;
var result = string.Empty;
// Loop through input and update result with shifted letters
foreach (var character in input)
{
if (!char.IsLetter(character))
{
// If the character isn't a letter, don't change it
result += character;
}
else
{
var newChar = (char) (character - shiftAmount);
// Adjust newChar to stay within this character range
if (newChar < (char.IsLower(character) ? 'a' : 'A')) newChar += (char) 26;
result += newChar;
}
}
return result;
}
Why don't you just use character's ASCII values. I would convert ciphertext to lower case first. For example a's asci value is 97. I would write a method to extract 97 every characters so a=0,b=1..... z=25. Then for every character in your ciphertext get -3 shifted value of that char.For example input char d should return value 0 which corresponds a.
I am currently writing a Caesar Cipher program in C# for my assignment and I am having a problem.
I am approaching this task using an array where I store the whole alphabet and I declare a shift variable which is defined by character index in the array - the iteration of a for loop. The shift calculation is done in a foreach loop, that fetches a character from a string that is read from a text file. Foreach loop is contained within a for loop that iterates to output every possible shift.
However, the problem is that when I try to access the character in an array by a value of my shift variable, the program doesn't seem to access the character I want, it just outputs the same character as in the original string.
This is the code for the program:
using System;
using System.IO;
public class caesar_shift
{
public static void Main()
{
string file = #"C:\Users\terasss2\Desktop\Programming and Data Structures\caesarShiftEncodedText.txt"; //String variable that stores a file location
string encrypted_text = File.ReadAllText(file); //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
char[] alphabet = new char[26]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for(int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
foreach(char c in encrypted_text)
{
character = c;
if(character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if(shift <= 0)
shift = shift + 26;
if(shift >= 26)
shift = shift - 26;
character = alphabet[shift]; //Set the character to a shifted letter by accessing the array element of a value shift
Console.WriteLine(character);
decoded_text = decoded_text + character;
}
Console.WriteLine("\nShift {0} \n {1}",i + 1, decoded_text);
}
}
}
I played a bit with your code. The following gives you the solution, but you have to take care: you couldonly use capital letters, because theres a difference in upper and lower charts. I used the ToUpper() method. Works fine for me. I think that's what your problem was.
public static void Main()
{
string encrypted_text = "BCD"; //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
encrypted_text = encrypted_text.ToUpper();
char[] alphabet = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for (int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
decoded_text = "";
foreach (char c in encrypted_text)
{
character = c;
if (character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if (shift <= 0)
shift = shift + 26;
if (shift >= 26)
shift = shift - 26;
decoded_text += alphabet[shift];
}
Console.WriteLine("\nShift {0} \n {1}", i + 1, decoded_text);
}
}
I took a look at your code and made a slight adjustment. First of all, I converted it to a method that lets you pass in the string and the amount you want to shift, so that you can either call it in a loop from 0 to 25 to see all the permutations, or you can just get a single value. I also check to see if each character is actually in the array, and if it isn't, then don't change it (in your code you were only checking for '\' and ' ' characters:
public static string ShiftText(string input, int shiftAmount)
{
if (input == null) return null;
char[] alphabet =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
shiftAmount %= 26; // Ensure shift is between 0 and 25
var shiftedText = string.Empty;
foreach (var character in input)
{
var index = Array.IndexOf(alphabet, character);
if (index < 0)
{
// This character isn't in the array, so don't change it
shiftedText += character;
}
else
{
var newIndex = index - shiftAmount;
// If it's negative, wrap around to end of array
if (newIndex < 0) newIndex += 26;
shiftedText += alphabet[newIndex];
}
}
return shiftedText;
}
But another way to do this that works for upper AND lower case, and which is less code, is to simply test if char.IsLetter(character), and then shift the ASCII value of the character within the same 0-25 range.
For example, this does the same as the code above, only it works for lower case letters as well. The difference here is that before we compare the character to our lowest valued character ('a' or 'A'), we test if char.IsLower() first. This way we stay within the ASCII range for this character set:
/// <summary>
/// This method takes the input string and shifts all letter characters
/// to the left (subtracts) by the amount specified in shiftAmount, so
/// if shiftAmount = 1, then 'M' becomes 'L', and 'a' becomes 'z'.
/// </summary>
/// <param name="input">The input string to apply changes to</param>
/// <param name="shiftAmount">A value from 0 to 25, used to shift the characters</param>
/// <returns>The modified (shifted) string</returns>
public static string ShiftText(string input, int shiftAmount)
{
if (input == null) return null;
// Ensure shift is between 0 and 25
shiftAmount %= 26;
var result = string.Empty;
// Loop through input and update result with shifted letters
foreach (var character in input)
{
if (!char.IsLetter(character))
{
// If the character isn't a letter, don't change it
result += character;
}
else
{
var newChar = (char) (character - shiftAmount);
// Adjust newChar to stay within this character range
if (newChar < (char.IsLower(character) ? 'a' : 'A')) newChar += (char) 26;
result += newChar;
}
}
return result;
}
Why don't you just use character's ASCII values. I would convert ciphertext to lower case first. For example a's asci value is 97. I would write a method to extract 97 every characters so a=0,b=1..... z=25. Then for every character in your ciphertext get -3 shifted value of that char.For example input char d should return value 0 which corresponds a.
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’:
case ‘u’:
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
You could do this:
char c = ...
bool isVowel = "aeiouAEIOU".IndexOf(c) >= 0;
or this:
char c = ...
bool isVowel = "aeiou".IndexOf(c.ToString(), StringComparison.InvariantCultureIgnoreCase) >= 0;
Once you add international support for things like éèe̋ȅëêĕe̊æøи etc. this string will get long, but the basic solution is the same.
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.)
No. You need to define first what you regard as a vowel and as a consonant. For example, in English, “y” could be a consonant (as in “yes”) or a vowel (as in “by”). Letters like “é” and “ü” are probably vowels in all languages in which they are used, but it seems that you did not consider them at all. Primarily, you should define why you wish to classify letters as consonants and vowels.
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);
The other methods given work. Here I am concerned with performance. For the two approaches I tested - using LINQ's Any method and using bit arithmetic, the use of bit arithmetic was more than ten times faster. Results:
Time for LINQ = 117 msec
Time for Bit masks = 8 msec
public static bool IsVowelLinq(char c)
{
char[] vowels = new[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
return vowels.Any(ch => ch == c);
}
private static int VowelMask = (1 << 1) | (1 << 5) | (1 << 9) | (1 << 15) | (1 << 21);
public static bool IsVowelBitArithmetic(char c)
{
// The OR with 0x20 lowercases the letters
// The test c > 64 rules out punctuation, digits, and control characters.
// An additional test would be required to eliminate characters above ASCII 127.
return (c > 64) && ((VowelMask & (1 << ((c | 0x20) % 32))) != 0);
}
See https://dotnetfiddle.net/WbPHU4 for the code in a test with timings.
The key idea with the bit mask is that the second bit is set for 'a', the sixth bit is set for 'e', etc. Then you take the letter, shift left by its ASCII value as an integer, and see if that bit in the mask is set. One bit is set in the mask for each vowel, and the OR operation performs the lowercasing of the letter first.
You can use "IsVowel" as you wanted. However the only thing is there is likely no default C# library or function that already does this out of the box, well if this is what you wanted. You will need to write a util method for this.
bool a = isVowel('A');//example method call
public bool isVowel(char charValue){
char[] vowelList = {'a', 'e', 'i', 'o', 'u'};
char casedChar = char.ToLower(charValue);//handle simple and capital vowels
foreach(char vowel in vowelList){
if(vowel == casedChar){
return true;
}
}
return false;
}
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();
}
}
Why not create an array of the vowels/consonants and check if the value is in the array?
You can do something like this in.
private bool IsCharacterAVowel(char c)
{
string vowels = "aeiou";
return vowels.IndexOf(c.ToString(),StringComparison.InvariantCultureIgnoreCase) >= 0;
}
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
return "aeiou".Any( c => c.Equals( Char.ToLowerInvariant( myChar ) ) );
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();
Look at this code to check for both Vowel and Consonant , C#
private static void Vowel(string value)
{
int vowel = 0;
foreach (var x in value.ToLower())
{
if (x.Equals('a') || x.Equals('e') || x.Equals('i') || x.Equals('o') || x.Equals('u'))
{
vowel += 1;
}
}
Console.WriteLine( vowel + " number of vowels");
}
private static void Consonant(string value)
{
int cont = 0;
foreach (var x in value.ToLower())
{
if (x > 'a' && x <= 'd' || x > 'e' && x < 'i' || x > 'j' && x < 'o' || x >= 'p' && x < 'u' || x > 'v' && x < 'z')
{
cont += 1;
}
}
Console.WriteLine(cont + " number of consonant");
}