将字符串 C# 中的所有数字相加
本文关键字:数字 字符串 | 更新日期: 2023-09-27 17:56:31
我想将所有数字相加在一个字符串中,
我相信这可以通过for loop
轻松完成。
我有:
int numbers = 1234512345;
for (int i = 0 ; i numbers.Length ; i++)
{
int total;
total = int [i];
}
但它不会起作用是有原因的,我非常困惑。
首先,您尝试迭代的"字符串"是一个整数。你可能的意思是
string numbers = "1234512345"
之后,有几种方法可以做到这一点,我个人最喜欢的是遍历字符串的每个字符,在其上使用 TryParse(如果字符串恰好是字母数字,这消除了任何问题)并汇总结果。见下文:
static void Main(string[] args) {
string numbers = "1234512345";
int total = 0;
int num; // out result
for (int i = 0; i < numbers.Length; i++) {
int.TryParse(numbers[i].ToString(), out num);
total += num; // will equal 30
}
Console.WriteLine(total);
total = 0;
string alphanumeric = "1@23451!23cf47c";
for (int i = 0; i < alphanumeric.Length; i++) {
int.TryParse(alphanumeric[i].ToString(), out num);
total += num; // will equal 32, non-numeric characters are ignored
}
Console.WriteLine(total);
Console.ReadLine();
}
就像其他人发布的那样,有几种方法可以解决这个问题,最重要的是个人喜好。
这应该可以做你想做的事
int total = 0;
foreach(char numchar in numbers)
{
total += (int)char.GetNumericValue(numchar);
}
编辑:
1线解决方案:
int total = numbers.Sum(x=> (int)char.GetNumericValue(x));
PS:为什么投反对票?