Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string to three doubles

Tags:

string

c#

split

I used C# and I would like split text comprised 3 doubles seperated by commas and spaces.

I did:

double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' })
                .Select(s => Convert.ToDouble(s))
                .ToArray();

when mystr = 33,44,55 for example it works fine (numbers seperated by only one comma)

Also, when mystr= 33 44 55 for example it works fine (numbers seperated by only one space)

BUT, when mystr= 33, 44, 55 it doesn't works (one space after the comma between each two numbers)

It also doesn't work when mystr = 33 44 55 (two spaces between each two numbers)

In both above examples I got an unhandled exception.

How can I solve it?

Thanks!

like image 669
Programmer Avatar asked Jul 22 '26 00:07

Programmer


1 Answers

You can add an option to remove empty entries in the Split:

var array = Array.ConvertAll(mystr.Split(new [] { ' ', ',' },
                             StringSplitOptions.RemoveEmptyEntries),
                             Convert.ToDouble);
like image 53
Jonathan Nappee Avatar answered Jul 23 '26 14:07

Jonathan Nappee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!