从句子中提取并添加数字 [英] extract and add number from a sentence
问题描述
您好,先生,
我正在编写一个应用程序.应用程序中的一种方法需要
1.从字符串中提取所有数字值.和
2.对所有提取的值求和,例如,
string somedata =我要1个可乐,1个大拇指等.";
谢谢everrne.
Hello Sir,
i am writing an application. One of the method in the application needs to
1. extract all number values from a string. and
2. Sum all the extracted values for example,
string somedata="I want 1 coke, 1 Thumbs up etc.";
Thank you everrne.
推荐答案
VJ的解决方案非常好.该解决方案的另一个版本可能对您有所帮助,
VJ''s solution is pretty good. Another version of the solution might be helpful to you,
namespace ConsoleApplication24
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string sentence = "I want 1 coke, 1 Thumbs up etc.";
string[] numbers = Regex.Split(sentence, @"\D+");
int parsedValue = default(int);
int result = numbers
.SkipWhile(item => string.IsNullOrEmpty(item))
.Sum(item => Int32.TryParse(item, out parsedValue) ? parsedValue : parsedValue);
Console.WriteLine("Result {0}", result);
}
}
}
希望对您有所帮助:)
Hope it helps :)
LINQ
和Regex
可以按以下方式使用.
LINQ
andRegex
can be used as follows.
string sentence = @"I want 1 coke, 1 Thumbs up etc.";
int sum = sentence
.Split(new char[]{' ','\t','\n','\r'}, StringSplitOptions.RemoveEmptyEntries)
.Where (s => Regex.IsMatch(s,@"\d+", RegexOptions.CultureInvariant))
.Sum (s => int.Parse(s));
Console.WriteLine (sum);
如果要处理十进制数字,则应相应地修改Regex
模式和Parse
.
替代
作为替代方法,可以使用Regex.Matches
方法仅提取数字并将其求和,如下所示:
If you want to handle decimal numbers then the Regex
pattern and Parse
are to be modified accordingly.
Alternative
As an alternative Regex.Matches
method can be used to extract only the numbers and sum them up as shown below:
string inputText = @"I want 1 coke, 1 Thumbs up etc. . 2. 2.0 .5 5.5 ";
var sum = Regex.Matches(inputText,@"(?:\d*\.\d+|\d+\.\d*|\d+)",
RegexOptions.CultureInvariant).OfType<Match>().Sum (m => double.Parse(m.Value));
Console.WriteLine (sum);
//Output
//12
这篇关于从句子中提取并添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!