我打印了字符串的Ascii字符,如何将值一起添加?

时间:2017-09-17 15:27:58

标签: c# .net

所以我明白了:

string name = "";
int sum = 0;
Console.WriteLine("What's you name?");
name = Console.ReadLine();
foreach (char c in name)
{
    Console.WriteLine((int)c);
}
sum = Console.ReadKey();

现在我的问题是,如何添加所有字符的ASCII码的值?

1 个答案:

答案 0 :(得分:0)

这很简单;

string name = "";
int sum = 0;
Console.WriteLine("What's you name?");
name = Console.ReadLine();
foreach (char c in name)
{
    Console.WriteLine((int)c);
    sum += (int) c; // This line will add all the values together
}
Console.WriteLine(sum.ToString()); // If you want to print to the console the sum.
// sum = // This line will prevent compilation. Does it need removing?
Console.ReadKey();

归功于@George Alexandria。

使用GetNumericValue函数代替也可能值得使用。 例如:

(int)Char.GetNumericValue(c);
相关问题