使用c#,我需要创建一个函数,可以获得字符串中以64开头的所有其他数字的总和。
"64.90.54.28.72.11.38.00.17.45"
64、54、72、38、17加起来就是245。
谁能帮我写声明?
在顶部包含Linq库。
using System.Linq;
对所有值求和的函数
public int SumNumbers(string s) => s
.Split(".") // split the string up by '.' to get the parts
.Where((value, index) => index % 2 == 0) // every 2nd part
.Select(x => int.Parse(x)) // convert the string to an int
.Sum(); // sum all the ints
用法:
var sum = SumNumbers("64.90.54.28.72.11.38.00.17.45");
如果这对我有帮助,请告诉我
try this
string num = "64.90.54.28.72.11.38.00.17.45";
//Since you need number starting with 64
if (!num.StartsWith("64"))
{
return;
}
//split numbers string on the basis of dot(.) separator. This will return string array.
string[] numArray = num.Split(new char[] { '.' });
int len = numArray.Length;
int result = 0;
for (int i = 0; i < len; i++)
{
//sum of numbers at even positions only required.
if (i % 2 == 0)
{
result += int.Parse(numArray[i]);//calculate sum
}
}
//print result.
Console.Write(result);