gpt4 book ai didi

c# - char 数组返回值如 5 0'w'

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:27 24 4
gpt4 key购买 nike

语言=C#软件 = Visual Studio 2015

在编写程序以查找给定字符串中的整数总和时,我遇到了问题。从字符串中获取每个字符时,我得到的值类似于 87'W',101'e' 而不是 'w' ,'e' . (也显示相应的 char 整数,这不是必需的)

程序:

public static void Main()     
{
string s = "Welcome to 2018";
int sumofInt = 0;
for (int i = 0; i < s.Length; i++)
{
if (Char.IsDigit(s[i]))
{
sumofInt += Convert.ToInt32(s[i]);
}
}
Console.WriteLine(sumofInt);

}

预计 o/p = 11实际 o/p = 203

此处 s[i] 的值如 50'2'

有什么办法可以避免字符的这种数字表示(50、87 等)? ?? (没有修剪)

最佳答案

试试这个:- 你正在获取 char 的 ASCII 表示形式作为一个整数

public static void Main()     
{
string s = "Welcome to 2018";
int sumofInt = 0;
for (int i = 0; i < s.Length; i++)
{
int val = (int)Char.GetNumericValue(s[i]);
if (Char.IsDigit(val))
{
sumofInt += Convert.ToInt32(val);
}
}
Console.WriteLine(sumofInt);

}

关于c# - char 数组返回值如 5 0'w',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com