Parse numbers from spans without allocations
C#
using System;
using System.Collections.Generic;
using System.Globalization;
/// <summary>Parses delimited numbers straight from a span, no substrings.</summary>
public static class SpanNumbers
{
public static List<double> ParseCsv(ReadOnlySpan<char> line, char separator = ',')
{
var values = new List<double>();
var start = 0;
for (var i = 0; i <= line.Length; i++)
{
if (i < line.Length && line[i] != separator)
{
continue;
}
var part = line[start..i].Trim();
if (!part.IsEmpty)
{
values.Add(double.Parse(part, NumberStyles.Float, CultureInfo.InvariantCulture));
}
start = i + 1;
}
return values;
}
public static void Main()
{
ReadOnlySpan<char> line = " 1.5, 2.25 ,, 3,4.75 ";
Console.WriteLine(string.Join(" | ", ParseCsv(line))); // 1.5 | 2.25 | 3 | 4.75
}
}