我正在尋找一種很好且方便的方法來將編碼為字串的陣列轉換回 C# 中的陣列。例如,將字串“[1.2,24.4,35.5,4.5]”轉換為浮點陣列
"[1.2,24.4,35.5,4.5]" -> [1.2,24.4,35.5,4.5]
uj5u.com熱心網友回復:
您提供的浮點陣列可以解釋為 JSON。您可以使用 JSON.NET 或首選的 JSON 序列化程式將其反序列化為 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]");
uj5u.com熱心網友回復:
如果您不打算實作更通用和更復雜的運算式解釋器。你可以用正則運算式和一些 linq 運算式來做到這一點。這可能是最簡單的。代碼如下:
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
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372365.html
上一篇:嘗試制作計算器
