Convert a Letter to its alphabet numerical Rank - c#

I am trying to convert a letter to its alphabet numerical order for example if I have an 'A' it will give me 00 or a 'C' 02
How can I code this in c# ?
EDIT : This is what I tried
I created this class :
public class AlphabetLetter
{
public char Letter {get; set;}
public int Rank {get; set;}
}
Those Two Lists :
public List<char> Letters = new List<char> {
'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'
};
public List<int> Ranks = new List<int> {
00,01,02,04,05,06,07,08,09,10,11,12,13,
14,15,16,17,18,19,20,21,22,23,24,25
};
public List<AlphabetLetter> Alphabet = new List<AlphabetLetter>( );
I created the Alphabet in my Constructor :
for (int i = 0; i < 25; i++)
{
Alphabet.Add(new AlphabetLetter { Rank = Ranks[i], Letter = Letters[i] });
And tried to match a char with this function :
public int Numberize(char Letter)
{
if (Letter != null)
{
foreach (AlphabetLetter _letter in Alphabet)
{
if (Letter == _letter.Letter)
{
return _letter.Rank;
}
else
{
return 896;
}
}
}
else {
return 999;
}
}
}
But this method is not working and is too tedious.
Any suggestions?

You start by simply getting its Unicode value:
int charValue = Convert.ToInt32('A');
Then account for where 'A' is on the Unicode table (65)
int rank = charValue - 65;
Note that this won't work for lower case letters, as they are in a different position. You could use ToLower or ToUpper on the string version of the character to nullify this (as in the other answer).

string yourLetter = "C";
int i = yourLetter.ToLower().ToCharArray()[0] - 'a';
This returns 2.
An explanation: The characters as char's are in sequential order. However, there are two sequences - of uppercase, and of lowercase. So first we convert it to lowercase.
Then change it to a character (by using the built in method for turning a string into a character array, and then taking the first and only one).
Then, using the fact that c# will happily treat the char as a number, subtract the first of the sequence from it.

You do not need any fancy conversion. Just subtract ascii A and add 1.
using System;
using System.IO;
public class P{
public static void Main(string[] args) {
var letter = 'C';
Console.WriteLine(letter - 'A' + 1);
}
}
If you want to pad with leading zeroes, use ToString with a format.
Console.WriteLine((letter - 'A' + 1).ToString("00"));

Related

Getting different values from convert char to integer

when I display the 'i' variable, which would be a char value
{
class Program {
static void Main(string[] args) {
var max = 0;
var lista = new char[] {
'1',
'2',
'3',
'4'
};
foreach(char i in lista) {
Console.WriteLine(i);
/* var hola = Convert.ToInt32(i);
Console.WriteLine(hola);*/
}
}
}
}
I get this:
> 1 2 3 4
However, when converting 'i' into an int
var max = 0;
var lista = new char[] {
'1',
'2',
'3',
'4'
};
foreach(char i in lista) {
var hola = Convert.ToInt32(i);
Console.WriteLine(hola);
}
I get this:
49 50 51 52
Any idea what could be the problem? I'd like to obtain the same values, so I can evaluate them as integers and obtain the biggest of them, but I can't.
When you convert a char to an int, you get the ASCII value of that character. The neat thing with these values is that they are sequential, so if you subtract the value of '0' (the 0 character), you can convert a character representing a digit to that digit:
var hola = i - '0';
If you want the literal character and not the ascii number of the character, use the ToString() method
var hola = Convert.ToInt32(i.ToString());
WriteLine method internally converts the parameters string. Thus you can have the value you want. ToInt method return the ASCII value of that char. You have to convert your i value to string i.ToString() or you can simply substract 48 from the converted value.

Getting a character's position that is randomly generated which as a string is stored in character array

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.

Check if a character is a vowel or consonant?

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");
}

Split string after variable amount of characters

I want to split my string called: invoerstring after a variable amount of characters (n is the number of characters when the string needs to be split)..
If the string length is shorter then the variable n, spaces need to be added until the string length = n. The result needs to be shown in a textfield called uitvoer.
This is what so far:
string invoerstring = invoer.Text;
if (invoerstring.Length < n)
{
invoerstring += "";
char[] myStrChars = invoerstring.ToCharArray();
}
if (invoerstring.Length == n)
{
string [] blok = invoerstring.Split();
foreach (string word in blok)
{
uitvoer.Text = word;
}
}
EDIT:
The solutions given above aren't completely doing the job for me, maybe it helps when I post the exercise:
|| crypt n m d text || text is padded with spaces until its length is
a multiple of n || the characters in text are circulary shifted in the
alphabet by the displacement d || example: if d = 1 then 'a' -> 'b' ,
'b' -> 'c' .... etc... 'z' -> 'a' || text is divided in blocks of
length n characters || inside every block of n the characters are
circulary shifted m times to the left || the shifted groups are
concatenated
I already solved the m and d only have to solve the n.
The solutions given above aren't completely doing the job for me, maybe it helps when I post the exercise:
|| crypt n m d text
|| text is padded with spaces until its length is a multiple of n
|| the characters in text are circulary shifted in the alphabet by the displacement d
|| example: if d = 1 then 'a' -> 'b' , 'b' -> 'c' .... etc... 'z' -> 'a'
|| text is divided in blocks of length n characters
|| inside every block of n the characters are circulary shifted m times to the left
|| the shifted groups are concatenated
I already solved the m and d only have to solve the n.
Here's the code you want, no need to go through a character array:
public static string EnsureExactLength(this string s, int length)
{
if (s == null)
throw new ArgumentNullException("null");
return s.PadRight(length).Substring(0, length);
}
You call it like this:
string s = "Test string".EnsureExactLength(4); // will return "Test"
string s = "Te".EnsureExactLength(4); // will return "Te "
You can find an example LINQPad program here.
Okay, I'm honestly not sure what the code you have above is doing because I see calls like Split() without any parameters, and stuff. But to meet the requirements, this one line should do:
string invoerstring = invoer.Text.PadRight(n, ' ').Substring(0, n);
the PadRight will make sure it's as long as n and the Substring will then return the portion of the string up to n.
If you then wanted that string in an array, because I see you have one at the end, you could do this:
invoerstring.ToArray();
Here is a LinqPad script:
void Main()
{
const string TEXT = "12345ABCDE12345ABCDE1234";
const int LENGTH = 5;
const char PAD = '#';
Enumerable.Range(0, TEXT.Length / LENGTH)
.Union(TEXT.Length < LENGTH ? new int[] { 1 } : new int[] {})
.Select((index, item) => TEXT.Length < LENGTH
? TEXT.PadRight(LENGTH, PAD)
: TEXT.Substring(index * LENGTH, LENGTH))
.Concat(TEXT.Length % LENGTH != 0
? new string[] { TEXT.Substring(TEXT.Length - (TEXT.Length % LENGTH)).PadRight(LENGTH, PAD) }
: new string[] { })
.Dump();
}

Convert a word into character array

How do I convert a word into a character array?
Lets say i have the word "Pneumonoultramicroscopicsilicovolcanoconiosis" yes this is a word ! I would like to take this word and assign a numerical value to it.
a = 1
b = 2
... z = 26
int alpha = 1;
int Bravo = 2;
basic code
if (testvalue == "a")
{
Debug.WriteLine("TRUE A was found in the string"); // true
FinalNumber = Alpha + FinalNumber;
Debug.WriteLine(FinalNumber);
}
if (testvalue == "b")
{
Debug.WriteLine("TRUE B was found in the string"); // true
FinalNumber = Bravo + FinalNumber;
Debug.WriteLine(FinalNumber);
}
My question is how do i get the the word "Pneumonoultramicroscopicsilicovolcanoconiosis" into a char string so that I can loop the letters one by one ?
thanks in advance
what about
char[] myArray = myString.ToCharArray();
But you don't actually need to do this if you want to iterate the string. You can simply do
for( int i = 0; i < myString.Length; i++ ){
if( myString[i] ... ){
//do what you want here
}
}
This works since the string class implements it's own indexer.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = word.ToCharArray();
Voilá!
you can use simple for loop.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
int wordCount = word.Length;
for(int wordIndex=0;wordIndex<wordCount; wordIndex++)
{
char c = word[wordIndex];
// your code
}
You can use the Linq Aggregate function to do this:
"wordsto".ToLower().Aggregate(0, (running, c) => running + c - 97);
(This particular example assumes you want to treat upper- and lower-case identically.)
The subtraction of 97 translates the ASCII value of the letters such that 'a' is zero. (Obviously subtract 96 if you want 'a' to be 1.)
you can use ToCharArray() method of string class
string strWord = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = strWord.ToCharArray();

Categories

Resources