Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string containing numbers separated by spaces into list of doubles c#

I have this string 05201 05594 05453 05521 05330 04952 04984 04526, and I need to turn it into an array of doubles.

How can I do so, without including the extra space at the end?


EDIT: Instead of turning into an array of doubles, I need to skip that step and add it to the end of an existing list of doubles

like image 267
user2705775 Avatar asked Dec 19 '22 19:12

user2705775


2 Answers

Try this:

var splitted = yourString.Split(new []{" "}, 
                                          StringSplitOptions.RemoveEmptyEntries);
existingListOfDoubles.AddRange(splitted.Select(double.Parse));

Try it at ideone. Edited to match question

like image 155
Kamil Budziewski Avatar answered Jan 12 '23 00:01

Kamil Budziewski


Split and convert. This assumes that your string contains only numbers.
Use a List<double> instead of an array for more advanced functionality

string inputString = "05201 05594 05453 05521 05330 04952 04984 04526 ";
string[] results = inputString.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
List<double> d = new List<double>();
d.AddRange(results.Select(x => Convert.ToDouble(x)));

Now if you want to store in an array you just convert back the List<double> to an array

double[] values = d.ToArray();

Instead if you want to append these results to an existing list of doubles

List<double> currentValues = new List<double>() {5345, 4213};
currentValues.AddRange(d);
like image 38
Steve Avatar answered Jan 11 '23 23:01

Steve