Convert character to its alphabet integer position?

 ̄綄美尐妖づ 提交于 2019-11-27 14:26:36

问题


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!]


回答1:


Programming 101:

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



回答2:


For lower and upper case:

int index = (int)c % 32;



回答3:


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



回答4:


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';
}



回答5:


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

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