Home > Software design >  Is there a C# equivalent to pythons ast.literal_eval function
Is there a C# equivalent to pythons ast.literal_eval function

Time:12-03

Im looking for a nice and convenient way to translate an array encoded as a string back to an array in C#. For example, convert the string "[1.2,24.4,35.5,4.5]" to an array of floats

"[1.2,24.4,35.5,4.5]" -> [1.2,24.4,35.5,4.5]

CodePudding user response:

The array of floats you have presented can be interpreted as JSON. You can use JSON.NET or your preferred JSON serializer to deserialize this to an array in C#.

JSON.NET:

float[] myArray = JsonConvert.DeserializeObject<float[]>("[1.2,24.4,35.5,4.5]");

System.Text.Json:

float[] myArray = JsonSerializer.Deserialize<float[]>("[1.2,24.4,35.5,4.5]");

CodePudding user response:

If you're not going to implement a expression interpreter that more general and more complex. You can do it with regular expression and some linq expression.It maybe simplest. the code as below:

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace StringToArray
{
    class Program
    {
        static void Main()
        {
            string testString = "[1.2, 24.4, 35.5, 4.5]";
            // It rough mean that have some digit and maybe have comma and some digit after comma.that repeat many times.
            var array = Regex.Matches(testString, @"(\d \.?\d*) ") 
                .Select(group => Convert.ToDouble(group.Value)) // Get digit string and convert to double
                .ToArray(); // Get float array
            foreach (var value in array)
            {
                Console.WriteLine(value); // Output: 1.2, 24.4, 35.5, 4.5
            }
        }
    }
}
  • Related