我正在尝试将字母转换为字母数字顺序,例如,如果我有一个' A'它会给我00或者C' 02
我如何在c#中编码?
编辑:这是我试过的
我创建了这个类:
public class AlphabetLetter
{
public char Letter {get; set;}
public int Rank {get; set;}
}
这两个名单:
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>( );
我在构造函数中创建了Alphabet:
for (int i = 0; i < 25; i++)
{
Alphabet.Add(new AlphabetLetter { Rank = Ranks[i], Letter = Letters[i] });
并尝试将char与此函数匹配:
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;
}
}
}
但是这种方法不起作用而且太繁琐了。
有什么建议吗?
答案 0 :(得分:3)
首先只需获取其Unicode值:
int charValue = Convert.ToInt32('A');
然后说明&#39; A&#39;在Unicode表(65)
上int rank = charValue - 65;
请注意,这不适用于小写字母,因为它们处于不同的位置。您可以在字符的字符串版本上使用ToLower
或ToUpper
来使其无效(如在其他答案中)。
答案 1 :(得分:2)
string yourLetter = "C";
int i = yourLetter.ToLower().ToCharArray()[0] - 'a';
返回2.
解释:char
&#39; s字符按顺序排列。但是,有两个序列 - 大写和小写。所以首先我们将它转换为小写。
然后将其更改为一个字符(通过使用内置方法将字符串转换为字符数组,然后取第一个且只有一个字符串。)
然后,使用c#很乐意将char作为数字处理的事实,从中减去第一个序列。
答案 2 :(得分:0)
您不需要任何花哨的转换。只需减去ascii A
并添加1。
using System;
using System.IO;
public class P{
public static void Main(string[] args) {
var letter = 'C';
Console.WriteLine(letter - 'A' + 1);
}
}
如果您想使用前导零填充,请使用格式为ToString
。
Console.WriteLine((letter - 'A' + 1).ToString("00"));