LINQ
and
Regex
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);
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);