I'm trying to find if there is a quick way to get the integer position of a character in the alphabet (C#).
I can simply create an array and get the position, but seems there must be a "nice and funky" way of acheiving this?
I've also looked at taking the ASCII position of the (uppercase) character in relation to "65"...but again, seems more work than it should be!
[English 26 letter alphabet only, no internationalisation required - and no, this is not homework!]
Programming 101:
char c = 'A';
//char c = 'b'; you may use lower case character.
int index = char.ToUpper(c) - 64;//index == 1
For lower and upper case:
int index = (int)c % 32;
Since char
and int
can be mixed and matched in calculations, you can treat you char as a number (which will for sure fall between well-known values):
char c = 'A';
var index = (c < 97 ? c - 64 : c - 96);
A clear, readable, 0-based implementation of @Ahmed's method with bounds checking.
/// <summary>
/// Converts a latin character to the corresponding letter's index in the standard Latin alphabet
/// </summary>
/// <param name="value">An upper- or lower-case Latin character</param>
/// <returns>The 0-based index of the letter in the Latin alphabet</returns>
private static int GetIndexInAlphabet(char value)
{
// Uses the uppercase character unicode code point. 'A' = U+0042 = 65, 'Z' = U+005A = 90
char upper = char.ToUpper(value);
if (upper < 'A' || upper > 'Z')
{
throw new ArgumentOutOfRangeException("value", "This method only accepts standard Latin characters.");
}
return (int)upper - (int)'A';
}
Here is a nice implementation for reading columns from an Excel string to a column number. kudos to @ahmed-kraiem & @vladimir for the answer above.
public int AddColFromLetter(string s)
{
int column = 0;
int iter = 1;
foreach (char c in s)
{
int index = char.ToUpper(c) - 64;//Ahmed KRAIEM
//int index = (int)c % 32;//Valdimir
if(iter == 1)
column += index;
if(iter > 1)
column += 25+ index;
iter++;
}
return column;
}
来源:https://stackoverflow.com/questions/20044730/convert-character-to-its-alphabet-integer-position