繁体   English   中英

收集十进制数中的数字 C#

[英]Collect the digits numbers in the decimal number C#

我想要一种从十进制数中删除逗号然后收集数字的方法。 例如,如果用户输入1,3 ,它将删除逗号并将13收集在一起。 我的意思是 1+3=4。 我可以使用修剪或更换吗?

public int AddSum(string x1)
{
    string x = x1.Trim();
        
    int n = Convert.ToInt32(x);
    return n;
}
public int AddSum(string x1)
{
    var digitFilter = new Regex(@"[^\d]");        
    return digitFilter.Replace(x1, "").Select(c => int.Parse(c)).Sum();
}

或者

public int AddSum(string x1)
{
    return x1.Where(c => char.IsDigit(c)).Select(c => c - '0').Sum();
}

如果您想遍历字符串中的字符并计算其中包含的数字总和,这很简单:

public static int SumOfDigits( string s ) {
  int n = 0;
  foreach ( char c in s ) {
    n += c >= '0' && c <= '9' // if the character is a decimal digit
      ? c - '0'               // - convert to its numeric value
      : 0                     // - otherwise, default to zero
      ;                       // and add that to 'n'
  }
  return n;
}

听起来您想采用逗号分隔的数字字符串,将数字相加,然后返回结果。

您要做的第一件事是对输入字符串使用Split()方法。 Split()方法采用输入字符串,根据字符将字符串拆分为字符串数组:

string[] numbers = x1.Split(',');

所以现在我们有一个名为numbers的字符串数组,其中包含每个数字。 接下来您要做的是创建一个空变量来保存运行总计:

int total = 0;

接下来是创建一个循环,循环遍历numbers数组,每次都将数字添加到运行总计中。 请记住, numbers字符串数组而不是数字。 所以我们必须使用intParse()方法将字符串转换为数字:

foreach (string number in numbers)
{
    total += int.Parse(number);
}

最后直接返回结果:

return total;

把它们放在一起,你得到了这个:

private static int AddSum(string x1)
{
    string[] numbers = x1.Split(',');
    int total = 0;
    
    foreach (string number in numbers)
    {
        total += int.Parse(number);
    }
    
    return total;
}

我希望这有助于澄清事情。 请记住,此方法不执行任何类型的错误检查,因此如果您的输入错误,您可能会遇到异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM