繁体   English   中英

根据 C# 中包含的字符为字符串赋值的简单方法是什么?

[英]What's an easy way to give a string a value based on the characters it contains in C#?

我试图根据字符串包含的字符来获得总和值。 字符值由我确定并且有些随意('A' = 1、'B' = 4、'C' = 2 等)。 例如,如果string s = "ABC" ,则int value = 7 ,因为 1 + 4 + 2 = 7。在 C# 中编写此代码的有效方法是什么?

现在我的代码如下所示:

//Declare variables
string name = JOHN
int i = 0;
int nameValue = 0;
string temp = "";
string[] nameArray;

//Convert name to string array so I can use String.Contains() to check what letters are in name
foreach (char c in name)
{
   temp += c.ToString();
   temp += ".";
}

temp = temp.Remove(temp.Length - 1, 1);
nameArray = temp.Split('.');            

//Determine nameValue by iterating through nameArray and checking each string
foreach (string s in nameArray)
{
   if (nameArray[i].Contains('A')) { nameValue += 1 }
   else if (nameArray[i].Contains('B')) { nameValue += 4 }
   else if (nameArray[i].Contains('C')) { nameValue += 2 }
   else if (nameArray[i].Contains('D')) { nameValue += 3 }
   .
   .
   .
   else if (nameArray[i].Contains('Y')) { nameValue += 7 }
   else if (nameArray[i].Contains('Z')) { nameValue += 5 }

   i++;
}

Console.WriteLine(nameValue);

我将字符串更改为字符串数组,因为我的名称中有重复的字母(即 Jill),并且我想给名称中的每个字母一个值。 如果我使用 String.Contains() 而不分隔每个字母,我认为它只会计算重复字母一次。

我觉得必须有一种更好的方法,而不是进行所有字符串操作并为字母表中的每个字母使用单独的条件语句,但我找不到任何东西。 谢谢。

如果您想将 map后续字符(例如'A'..'Z' )转换为 integer 值,我建议使用数组

  using System.Linq;

  ...

  int[] map = new int[] {
    //TODO: put corresponding integer values starting from 'A'
    4, 2, 3
  };  

  ...

  s = "ABC";

  int sum = s.Sum(c => map[c - 'A']);

一般情况下,如果要 map任意符号,可以使用字典

  using System.Linq;

  ...

  Dictionary<char, int> map = new Dictionary<char, int>() {
    //TODO: put all required pairs here
    {'A', 4},
    {'B', 2},
    {'C', 1},
    {'#', -123},
  };

  ...

  s = "ABC";

  // if there's no map (e.g. for '*'), we assume the value being 0
  int sum = s.Sum(c => map.TryGetValue(c, out int v) ? v : 0);   

http://www.asciitable.com/

你会看到国会大厦 A 是 65

string str = "Hi there";
foreach(char c in str.ToUpper())
{
    value += ((int)c) - 64;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM