Language =C# 软件 = Visual Studio 2015
在编写程序以查找给定字符串中的整数总和时,我遇到了问题。 从字符串中获取每个字符时,我得到的值是87'W',101'e'
而不是'w'
,'e'
.(显示字符的相应整数,这也是不需要的(
程序:
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等(的数字表示? ??(不修剪(
试试这个:-你正在获得字符的 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);
}
'0'..'9'
范围的典型技巧是减去'0'
:
char digit = '7';
int value = digit - '0';
您可以在Linq的帮助下简化代码:
public static void Main() {
string s = "Welcome to 2018";
int sumofInt = s.Sum(c => c >= '0' && c <= '9' // do we have digit?
? c - '0' // if true, take its value
: 0); // else 0
Console.WriteLine(sumofInt);
}