该程序应将数字翻译成字母。如何?

时间:2017-04-11 05:53:55

标签: c# console

我的代码应该将字母翻译成数字。如何将数字翻译成字母?

string strs = Console.ReadLine();
                Dictionary<char, int> dic = new Dictionary<char, int>
        {
            {'A', 1},
            {'B', 2},
            {'C', 3},

        };

                for (int i = 0; i < strs.Length; i++)
                {
                    int val = 0;
                    if (dic.TryGetValue(strs[i], out val))
                        strs = strs.Replace(strs[i].ToString(), val.ToString());
                }



                Console.WriteLine(strs);

2 个答案:

答案 0 :(得分:2)

您实际上不需要为此使用字典。只需使用char类型和int类型,就可以相对轻松地完成此操作。请注意,这假设您的示例始终使用A-Z中的大写字符。如果你需要比这更强大的东西,你显然需要更复杂的逻辑。

public static class Converter
{
    public static int? ConvertToInt(char value, char lowerLimit, char upperLimit)
    {
        // If the value provided is outside acceptable ranges, then just return
        // null. Note the int? signature - nullable integer. You could also swap
        // this with 0.
        if (value < lowerLimit || value > upperLimit)
            return null;

        // 'A' is 65. Substracting 64 gives us 1.
        return ((int)value) - 64;
    }

    public static char? ConvertToChar(int value, int lowerLimit, int upperLimit)
    {
        // Basically the same as above, but with char? instead of int?
        if (value < lowerLimit || value > upperLimit)
            return null;

        // 'A' is 65. Substracting 64 gives us 1.
        return ((char)value) + 64;
    }
}

用法看起来像这样:

// = 1
int? a = Converter.ConvertToInt('A', 'A', 'F');
char? A = Converter.ConvertToChar(a, 1, (int)('F' - 'A'));

请注意,您需要进行一定程度的字符串索引,但这会给您一个很好的结构,因为您不需要在任何地方存储任何状态 - 您可以将其作为方法调用的一部分。< / p>

答案 1 :(得分:1)

所有字符都在映射到数值的计算机中。因此,要获取字符的数值,您可以执行以下操作:

int valueOfA= 'A';

原来它是65.所以以下内容将起作用:

var text = "ABBA";
foreach (var character in text.ToCharArray())
{
    int result=character;
    Console.WriteLine(result-64);
}

对于小写,它是33.因此,如果你需要将所有的“1”处理为1,那么你可以使用:

var text = "aBBA".ToUpper();
foreach (var character in text.ToCharArray())
{
    int result=character;
    Console.WriteLine(result-64);
}

否则你需要做一些检查。

另请注意,1的字符不一定是1的值。(实际上它是-15)

相关问题