首页 > 解决方案 > 如何对字符串中的所有百分比值求和?

问题描述

我正在阅读一个字段,其中该字段中的字符串是动态的。这意味着文本会不时更改,但文本中始终存在价值。我想在这个字符串中找到值并将它们总结起来。值后面有一个百分比,有时数字和百分比符号之间有空格,我想从字符串中找到所有值并将它们加起来。我已经尝试了以下方法,但这不起作用

    var values = inputString.Split(' ')
                      .Where(s => s.Contains('%'))
                      .Select(s => s.Trim('%'));

    var result = values.Sum(val => val.ToDecimal());

举个例子,这里是输入字符串的样子

- the element contains 1% and also 2% of the something
- Only 1% of A
- Only 5 % of A
- the element contains 1% of A, 2% of B and also 2 % of C ...

我只想总结附加到 % 符号的值。

关于如何实现这一目标的任何想法?

标签: c#

解决方案


我使用正则表达式来解决这个问题:

private int CalculateSum(string text)
{
    Match match = new Regex(@"\d+\s*%").Match(text);

    int sum = 0;

    while (match.Success)
    {
        sum += int.Parse(match.Value.Substring(0, match.Value.Length - 1).Trim());
        match = match.NextMatch();
    }

    return sum;
}

如果你也想处理双精度值,你可以使用下一个函数:

double CalculateDoubleSum(string text)
{
    Match match = new Regex(@"\d+(\.\d+)?\s*%").Match(text);

    double sum = 0;

    while (match.Success)
    {
        sum += double.Parse(match.Value.Substring(0, match.Value.Length - 1).Trim());
        match = match.NextMatch();
    }

    return sum;
}

推荐阅读