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.
IEnumerable<double> doubles = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select<string, double>(double.Parse)
Updated to use StringSplitOptions.RemoveEmptyEntries as the number of spaces changes
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); }
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]);
Do you want effective .....
var regex = new Regex(@"([\d\.]+)", RegexOptions.Compiled) var matches = regex.Matches(input);
Source: https://habr.com/ru/post/1301011/More articles:How to quote in HTML (not blockquote)? - htmlIs there a function to create the file name of the copied file? - c #Download only modified git files - gitUsing cURL Handle as Array Key - phphttps://translate.googleusercontent.com/translate_c?depth=1&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1301010/using-accessor-methods-to-set-ivars&usg=ALkJrhgSpTVep18Q0PWfduICiLp-RNio_APreventing UpdatePanel - c #Parsing multiple paired numbers from a string in C # - c #Delete dir with nAnt and exclude subfolder? - nantFix PE-executable - cjquery + flash: search for a plugin that resizes images before loading - jqueryAll Articles