使用 char 值与 C# 中的变量名称进行比较

本文关键字:比较 变量名 char 值与 使用 | 更新日期: 2023-09-27 18:31:53

我正在尝试使用 c# 解决欧拉项目中的一个问题(问题 22)。虽然我遇到了一个问题。值得注意的是,我对编程相对较新,尤其是 c#。

我需要为我拥有的一组字符串想出一个单词分数。这涉及将单词中每个字母的分数相加,例如 a=1、b=2、c=3 等。为此,我将字母表的所有 26 个字母指定为具有相关分数的变量。然后,我想将单词中的每个字母与同名的相关变量进行比较。但是,我剩下的是 char 数据类型,这是我将字符与相关变量进行比较的最佳方法,然后在整数计算中使用变量值。我已经在下面包含了到目前为止的代码,问题发生在最后 2 行(不包括大括号)。(我快速浏览了一下,似乎这在 c++ 中不受支持,尽管我不确定 c#)。任何帮助将不胜感激。

string[] lines = File.ReadAllLines(@"C:'Users'john'Downloads'names.txt");
//Console.WriteLine(lines[1]);
char[] delimiterChars = { ',', ''t' };
string text = lines[0];
string[] names = text.Split(delimiterChars);
Console.WriteLine("{0} words in text:", names.Length);
Array.Sort(names);
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int e = 5;
int f = 6;
int g = 7;
int h = 8;
int i = 9;
int j = 10;
int k = 11;
int l = 12;
int m = 13;
int n = 14;
int o = 15;
int p = 16;
int q = 17;
int r = 18;
int s = 19;
int t = 20;
int u = 21;
int v = 22;
int w = 23;
int x = 24;
int y = 25;
int z = 26;
int[] nameTotal;
for (int count = 0; count < names.Length; count++)
{
    string name = names[count];
    int total = 0;
    for (int count2 = 0; count2 < name.Length; count2++)
    {             
        nameTotal[count] = name.Substring(count2) + total;
        total = total + nameTotal[count];
    }
}

使用 char 值与 C# 中的变量名称进行比较

您可以通过利用标准 ASCII 表的布局来执行此操作。

在 ASCII 中,"a"字符的十进制值为 97。 然后小写字母一直持续到 122。

因此,您可以使用以下命令轻松地将"a"字符值转换为所需的值:

char charToConvert = 'a';
int requiredValue = (int)charToConvert - 96;
如果要

计算名称中字母的总和,也可以使用 Linq(仅举个例子):

string name = "ABCD";
int sum = name.Select(letter => letter - 'A' + 1).Sum();  

可以使用字母执行计算,就像在 C# 中使用整数一样。Select 方法(它是 Linq 中的扩展方法)将字符串的每个字母投影到其对应的值。然后通过扩展方法 Sum() 对这些值求和。

编辑:正如jlafay指出的那样,您可以省略Select调用并将投影放入Sum方法中:

name.Sum(letter => letter - 'A' + 1)

关于你最初的问题:即使有反射,你也无法访问局部变量的名称。该信息不包含在已编译代码的元数据中。

与其为每个字母分配 26 个变量,不如创建一个IDictionary<TKey, TValue>,其中TKey是字符,TValue是您分配的任何值。然后,您可以通过更轻松地传入字符来访问该值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SO
{
    static class Program
    {
        static void Main()
        {
            WebClient wc = new WebClient();
            var text = wc.DownloadString("http://projecteuler.net/project/names.txt");
            var names = Regex.Matches(text, "[A-Z]+").Cast<Match>()
                .Select(x => x.Value)
                .OrderBy(x => x)
                .Select((name, inx) => new
                {
                    Name = name,
                    Score = name.Sum(c => c - 'A' + 1) * (inx + 1)
                });
            foreach (var n in names)
            {
                Console.WriteLine("{0}: {1}", n.Name, n.Score);
            }
        }
    }
}