4

Possible Duplicate:
Parse multiple doubles from string in C#

Say I have a line of text that looks as follows:

"45.690 24.1023 .09223 4.1334"

What would be the most efficient way, in C#, to extract just the numbers from this line? The number of spaces between each number varies and is unpredictable from line to line. I have to do this thousands of times, so efficiency is key.

Thanks.

Community
  • 1
  • 1
Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • 4
    Exact duplicate: http://stackoverflow.com/questions/1406129 – dtb Feb 11 '10 at 16:03
  • What is your desired extract? 456902410230922341334? – Ta01 Feb 11 '10 at 16:03
  • You might find some useful material here: http://stackoverflow.com/questions/1561273/parse-an-integer-from-a-string-with-trailing-garbage, though those solutions are for integers only. – finnw Feb 11 '10 at 16:04

4 Answers4

5
IEnumerable<double> doubles = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                               .Select<string, double>(double.Parse)

Updated to use StringSplitOptions.RemoveEmptyEntries since the number of spaces varies

Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
2

Use a Regex split. This will allow you to split on any whitespace of any length between your numbers:

string input = "45.690 24.1023 .09223 4.1334";
string pattern = "\\s*";            // Split on whitepsace

string[] substrings = Regex.Split(input, pattern);
foreach (string match in substrings)
{
   Console.WriteLine("'{0}'", match);
}
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
0

I haven't measured, but simplicity is key if you are trying to be efficient so probably something like

var chars = new List<char>();
for( int i =0; i < numChars; ++i )
    if( char.IsDigit( text[i] ) )
        chars.Add(text[i]);
µBio
  • 10,668
  • 6
  • 38
  • 56
0

You want efficient.....

var regex = new Regex(@"([\d\.]+)",  RegexOptions.Compiled)
var matches = regex.Matches(input);
Sky Sanders
  • 36,396
  • 8
  • 69
  • 90