Parsing multiple paired numbers from a string in C #

I have a string containing a known number of double values. What is the cleanest way (via C #) to parse a string and connect the results to comparable scalar variables. Basically, I want to make the equivalent of this sscanf operator, but in C #:

 sscanf( textBuff, "%lg %lg %lg %lg %lg %lg", &X, &Y, &Z, &I, &J, &K ); 

... assuming that " textBuff " may contain the following:

  "-1.123 4.234 34.12 126.4 99 22"

... and that the number of space characters between each value can vary.

Thanks for any pointers.

+3
source share
3 answers
 string textBuff = "-1.123 4.234 34.12 126.4 99 22"; double[] result = textBuff .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => double.Parse(s)) .ToArray(); double x = result[0]; // ... double k = result[5]; 

or

 string textBuff = "-1.123 4.234 34.12 126.4 99 22"; string[] result = textBuff .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); double x = double.Parse(result[0]); // ... double k = double.Parse(result[5]); 
+18
source

You can use String.Split ('', StringSplitOptions.RemoveEmptyEntries) to split it into "single values". Then it's direct Double.Parse (or TryParse)

+4
source
 foreach( Match m in Regex.Matches(inputString, @"[-+]?\d+(?:\.\d+)?") ) DoSomething(m.Value); 
0
source

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


All Articles