Example:
List<string> letters = new List<string>();
letters.Add("A");
letters.Add("B");
letters.Add("C");
letters.Add("D");
letters.Add("E");
letters.Add("F");
letters.Add("G");
letters.Add("H");
letters.Add("I");
letters.Add("J");
letters.Add("K");
letters.Add("L");
letters.Add("M");
letters.Add("N");
letters.Add("O");
letters.Add("P");
letters.Add("Q");
letters.Add("R");
letters.Add("S");
letters.Add("T");
letters.Add("U");
letters.Add("V");
letters.Add("W");
letters.Add("X");
letters.Add("Y");
letters.Add("Z");
If I had somebody input a letter in the list, how could I tell which number of the alphabet it is
CodePudding user response:
You can request the zero-based index of a listitem by using List<T>.IndexOf(item)
.
However, for finding out what letter of the alphabet a character is I suggest converting the char to a byte and substracting the offset: (byte)[charToCheck]-96
, e.g. (byte)'a'-96
will return 1
You could write an extension method for this purpose like so:
// startingIndex specifies if the first character of the alphabet should be 0 or any other number
public static Int32 GetPositionInAlphabet(this char character, Int32 startingIndex = 0)
{
return (byte)Char.ToLower(character) - 97 startingIndex;
}
CodePudding user response:
It is letters.IndexOf(theletter) 1
IndexOf
returns the 0-based index, that is, 0 for the first item, 1 for the second item, etc. This is why the 1 is needed.