开发者

How to split a string into doubles and add them to array C#

I have a string like

"1.898, -1.456, 233.556, 34546.8"

How would I make an array of doubles in C# Do I have to use regex or split function?

I was trying something like:

string[] aux = ORIG开发者_StackOverflow社区INALtext.Split(',');
foreach (string val in aux)
{
   double value = double.Parse(val);
   Console.WriteLine(value);

}


double[] doubles = Array.ConvertAll(myDoubles.Split(','), double.Parse);

Or using LINQ

double[] doubles = myDoubles.Split(',').Select(double.Parse).ToArray();


string[] str = "1.898, -1.456, 233.556, 34546.8".Split(',');
double[] doubles = new double[str.Length];
for (int i = 0; i < str.Length; i++)
{
    doubles[i] = double.Parse(str[i]);
}


A few different ways:

ORIGINALtext.Split(',').Select(s =>
        float.Parse(s, CultureInfo.InvariantCulture));

ORIGINALtext.Split(',').Select(s =>
        Convert.ToDouble(s, CultureInfo.InvariantCulture));

foreach (string s in ORIGINALtext.Split(',')) {
    double x;
    if (double.TryParse(s, NumberStyles.Number,
                        CultureInfo.InvariantCulture, out x)) {
        yield return x;
    }
}

CultureInfo.InvariantCulture will make the compiler use a consistent format across all country lines. (Dot for decimal separator, Comma for thousand separator, etc.)

With NumberStyles, you can control which number styles you want to allow (surrounding white space, signed numbers, thousand separator, etc.). You can also pass it to float.Parse, but not to Convert.ToDouble.


You could split the string using the comma delimiter and then use Double.Parse() to parse the individual string elements into doubles.

var s = "1.898, -1.456, 233.556, 34546.8";
var split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var doubles = new double[s.Length];
for(var i=0; i < split.Length; i++) {
    doubles[i] = Double.Parse(split[i].Trim());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜