c# - 如何对字符串中的所有百分比值求和?
问题描述
我正在阅读一个字段,其中该字段中的字符串是动态的。这意味着文本会不时更改,但文本中始终存在价值。我想在这个字符串中找到值并将它们总结起来。值后面有一个百分比,有时数字和百分比符号之间有空格,我想从字符串中找到所有值并将它们加起来。我已经尝试了以下方法,但这不起作用
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 ...
我只想总结附加到 % 符号的值。
关于如何实现这一目标的任何想法?
解决方案
我使用正则表达式来解决这个问题:
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;
}
推荐阅读
- java - 通过组合前瞻和后视使用正则表达式在java中拆分字符串
- python - 如何在 Mac OSX 中同时运行多个 python 文件
- c# - 如何将现有 SQLite 数据库放入应用程序的本地数据存储中,以便在通用 Windows 平台应用程序中使用?
- python - 使用 pd.read_csv(),指定数据为 np.float32,但得到字符串
- react-native - 如何在我的 react-native 项目中添加 ssl.cer 文件(无法在 react-native-android 中发出 https 请求)
- node.js - Docker 映像无法运行安装后脚本并出现错误 my_pck@2.0.0~postinstall: cannot run in wd my_pck@2.0.0 node symLink.js (wd=/build)
- html - 如何用按钮修复响应式输入框?
- python - 在 apache-nifi 中使用 executescript 处理器更新 csv 值失败
- php - 如何使用数组回显多个图像
- kubernetes - 通过从外部 IP aws/nvidia clara 访问无法使“storescu”正常工作