Skip to content

Instantly share code, notes, and snippets.

@Curtis-64
Created January 25, 2024 01:29
Show Gist options
  • Save Curtis-64/490f63d357ca6dc330d78e85a3bc60c7 to your computer and use it in GitHub Desktop.
Save Curtis-64/490f63d357ca6dc330d78e85a3bc60c7 to your computer and use it in GitHub Desktop.
Bracketed Float To String
Brackted to Float Developed Solution by Corp AI GPT & Curtis White, Senior Software Engineer, Prompt Engineer
Corp AI
https://chat.openai.com/g/g-A46CKCg3r-hacker-gnome-corp-ai-autonomous-agi
Solution 1 optimized for conciceness.
----
using System;
using System.Globalization;
using System.Linq;
public static class StringExtensions
{
public static float[] ToFloatArray(this string data) => data[1..^1].Split(',').Select(s => float.Parse(s, CultureInfo.InvariantCulture)).ToArray();
}
class Program
{
static void Main()
{
Console.WriteLine(string.Join(", ", "[10,20.5,30.88,1.234e5,-0.12345]".ToFloatArray()));
}
}
---
Solution 2 optimized for performance.
using System;
using System.Globalization;
public static class StringExtensions
{
public static float[] ToFloatArray(this string bracketedString)
{
// Validate the input is in the expected format.
if (bracketedString == null || bracketedString.Length < 3 || bracketedString[0] != '[' || bracketedString[^1] != ']')
throw new ArgumentException("String must be non-null, non-empty, and enclosed in brackets.");
// Prepare for parsing.
var numbers = bracketedString.AsSpan(1, bracketedString.Length - 2);
var result = new float[CountCommas(numbers) + 1];
// Parse the numbers.
int resultIndex = 0;
while (!numbers.IsEmpty)
{
var endIndex = numbers.IndexOf(',');
var slice = endIndex == -1 ? numbers : numbers.Slice(0, endIndex);
if (float.TryParse(slice, NumberStyles.Float, CultureInfo.InvariantCulture, out float number))
{
result[resultIndex++] = number;
}
else
{
throw new FormatException($"The segment '{slice.ToString()}' could not be parsed as a float.");
}
numbers = endIndex == -1 ? ReadOnlySpan<char>.Empty : numbers.Slice(endIndex + 1);
}
return result;
}
private static int CountCommas(ReadOnlySpan<char> span)
{
int count = 0;
for (int i = 0; i < span.Length; i++)
{
if (span[i] == ',') count++;
}
return count;
}
}
public class Program
{
public static void Main()
{
string bracketedData = "[10,20.5,30.88,1.234e5,-0.12345]";
var floatArray = bracketedData.ToFloatArray();
Console.WriteLine("Extracted float array:");
Console.WriteLine(string.Join(", ", floatArray));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment