Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

VJ's solution is pretty good. Another version of the solution might be helpful to you,

C#
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 :)
 
Share this answer
 
Comments
VJ Reddy 14-May-12 21:59pm    
Good alternative. 5!
Mohammad A Rahman 14-May-12 22:01pm    
Thanks VJ :)
(__Aaron__) 15-May-12 0:30am    
Thank you sir.
LINQ and Regex can be used as follows.
C#
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:
C#
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
 
Share this answer
 
v5
Comments
Mohammad A Rahman 14-May-12 21:56pm    
Good answer :)
VJ Reddy 15-May-12 0:01am    
Thank you, Rahman :)
VJ Reddy 14-May-12 23:08pm    
To the down voted (Gold) member
Can you please give the reason for down voting so that I can know the deficiency and try to improve myself and can you please post your solution which is better than this so that it will be helpful for me, OP and others who may view this post.

Thank you very much.
Mohammad A Rahman 14-May-12 23:52pm    
Just ignore them mate :) There is always someone :( I think your solution is pretty good, as you had my 5 :)
VJ Reddy 15-May-12 0:01am    
Thank you, Rahman :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900