Convert character to its alphabet integer position?

喜欢而已 提交于 2019-11-28 22:52:51

Programming 101:

char c = 'A';
//char c = 'b'; you may use lower case character.
int index = char.ToUpper(c) - 64;//index == 1
Vladimir

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;
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!