C # - Parsing a line of text - what's the best way to do this?

Possible duplicate:
Parsing multiple doubles from a string in C #

Let's say I have a line of text that looks like this:

"45.690 24.1023.09223 4.1334"

What would be the most efficient way in C # to extract only 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.

+4
source share
4 answers
IEnumerable<double> doubles = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select<string, double>(double.Parse) 

Updated to use StringSplitOptions.RemoveEmptyEntries as the number of spaces changes

+5
source

Use split regex. This will allow you to split any spaces 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); } 
+2
source

I have not measured, but simplicity is key, if you are trying to be effective, maybe something like

 var chars = new List<char>(); for( int i =0; i < numChars; ++i ) if( char.IsDigit( text[i] ) ) chars.Add(text[i]); 
0
source

Do you want effective .....

 var regex = new Regex(@"([\d\.]+)", RegexOptions.Compiled) var matches = regex.Matches(input); 
0
source

Source: https://habr.com/ru/post/1301011/


All Articles