Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm creating a basic caesar cipher encryption/decryption. I'm having an issue where a random "u" is appearing instead of a space.. Any not sure how to correct this, any advice would be very much appreciated.
// Decryption Method //
static void decryption() {
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("\n*********************************** Decryption *********************************");
Console.ResetColor();
//pulls getPath from varables class
string path = globalVars.getPath();
string fileContent = "";
string encrypted_text = System.IO.File.ReadAllText(path); //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("\n\nShift {0} \n\n {1}", i + 1, decoded_text);
fileContent += "Shift " + (i + 1).ToString() + "\r\n" + decoded_text + "\r\n";
}
// Save Decrypted Output to .TXT file - allows user to choose save path within filesystem.
string filename;
string savePath;
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("\nWhat do you want to name your file??");
Console.ResetColor();
filename = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("Where would you like to save your file??");
Console.ResetColor();
savePath = Console.ReadLine();
File.WriteAllText(savePath + filename + ".txt", fileContent);
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("File Saved");
Console.WriteLine(Console.Read());
}
Please see below for images of both input and output text
Your bug originates from the fact that Array.IndexOf returns -1 (ie, equivalent to z) if the character is not present in the array, so giving a shift of -1 - i. In particular, the new line characters every 20 characters are causing problems.
I would suggest your check of
if (character == '\'' || character == ' ')
continue;
be replaced with a check
if (!alphabet.Contains(character))
{
decoded_text += character;
continue;
}
Which is much more robust, and in particular works for characters such as \n, or \r followed by \n (\r\n is a line break on windows). Adding the character to the output is optional, but maybe helpful.
Your problem is in the new line characters, which this line:
if (character == '\'' || character == ' ') continue;
does not check.
In that case, Array.IndexOf will return -1. Since your text is correctly decrypted when i == 5 (i.e. "Shift 6"), this will, for unknown characters, give you alphabet[20], which is U. The lines in your input file are 20 characters long and, indeed, the first wrong U appears after 20 characters in the output as well: THEINCREDIBLELEGACYOUFTHE...
You should instead check if Array.IndexOf(...) >= 0.
I don't have a direct answer to your question, suffice to say that it is likely something to do with the way you shift bytes. I do, however, want to share a byte cipher that I found some time ago on the internet, which does exactly what you're trying to do, but in very few lines of code: Original Source Here
Despite the biased downvotes, the snippet of code is actually very good, and works well for simple obfuscation tactics. Here is the code just in case the link were to die:
public static class SimpleByteCipher
{
public static byte[] EncryptStringToByteArray( string data , string password , uint seed)
{
byte[] bytes = Encoding.ASCII.GetBytes( data );
byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
int passwordShiftIndex = 0;
for( int i = 0; i < bytes.Length; i++ )
{
bytes[ i ] = ( byte )( bytes[ i ] + passwordBytes[ passwordShiftIndex ] + seed );
passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
}
return bytes;
}
public static string DecryptByteArrayToString( byte[] data , string password , uint seed)
{
byte[] bytes = data;
byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
int passwordShiftIndex = 0;
for( int i = 0; i < bytes.Length; i++ )
{
bytes[ i ] = ( byte )( bytes[ i ] - passwordBytes[ passwordShiftIndex ] - seed );
passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
}
return Encoding.ASCII.GetString( bytes );
}
}
Again, I know this is not a direct answer, but perhaps you can learn something from the way that user did it.
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"
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.
I have created a program that randomly generates a letter from a given word which is stored in a character data type array.
For example:
strong and r is generated and also displayed.
How can I get the position of r and also display it?
s - 1, t - 2, r -3, o - 4, n - 5, g -6. The letter r is the 3rd letter.
Since I have stored the word in character array, array by default has its index value starting from 0 and I can't reset it.
I have got r generated, how can I get and display its position without tampering with my character array?
Is there anyway where I can compare the randomly generated r and its position?
Array.IndexOf Method (Array, Object) is your friend:
int index = Array.IndexOf(characters, randomChar) + 1;
//+1 at the end because indexes are zero-based
You can use Array.IndexOf as follows:
var word = new[] { 's', 't', 'r', 'o', 'n', 'g' };
var character = 'r';
var position = Array.IndexOf(word, character);
Note: Since arrays are zero indexed, you will need to add 1 to position to get 3 as IndexOf will return 2 in this example.
If you want to show ALL positions of a given character then you will need to create a method to find them (something like this although it could probably be improved):
public static IEnumerable<int> AllIndexesOf<T>(this T[] source, T value)
where T : IComparable<T>
{
if (Array.IndexOf(source, value) == -1)
{
yield return -1;
yield break;
}
var position = Array.IndexOf(source, value);
while (position > 0)
{
yield return position;
position = Array.IndexOf(source, value, position + 1);
}
yield break;
}
Which you can then use as follows:
var word = new[] { 's', 't', 'r', 'o', 'n', 'g', 'e', 'r' };
var character = 'r';
foreach (var position in word.AllIndexesOf(character))
{
Console.WriteLine(position.ToString());
}
Since you don't supply any code, let me just show how I would implement it:
public static string RandomChar(string s) {
Random r = new Random();
int i = r.Next(s.Length);
return s[i] + " - " + (i+1);
}
This picks an index at random and returns the character at that index as well as the 1-based index of the character, e.g. "r - 3".
Call it with:
string result = RandomChar("strong");
// Do something with the result, e.g. Console.WriteLine(result).
Is it imperative that you do this is C#? Because you can do this using php:
<?php
$mystring = 'strong';
$findme = 'r';
$pos = strpos($mystring, $findme);
$posadj = $pos +1; //this will offset because the array starts at 0.
// must use ===
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos which when offset is really $pos1.";
}
?>
The results of this snippet are $pos = 2 and $pos1 = 3.
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");
}