[英]C#. How do i turn a String into a Double array?
class Program {
public static void Main (string[] args) {
string S1 = Console.ReadLine();
string S2 = Console.ReadLine();
double [] D1 = Array.ConvertAll(S1.Split(' '), Double.Parse);
double [] D2 = Array.ConvertAll(S2.Split(' '), Double.Parse);
The final part of it isn't working, for some reason.由于某种原因,它的最后一部分不起作用。 After i enter the imput, the console says我输入输入后,控制台说
Unhandled exception.未处理的异常。 System.FormatException: Input string was not in a correct format. System.FormatException:输入字符串的格式不正确。 at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Double.Parse(String s) at System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter) at Program.Main(String[] args) in /home/runner/distancia-entre-dois-pontos/main.cs:line 9在 System.Number.ThrowOverflowOrFormatException(ParsingStatus 状态,TypeCode 类型) 在 System.Double.Parse(String s) 在 System.Array.ConvertAll[TInput,TOutput](TInput[] 数组,Converter`2 转换器) 在 Program.Main( /home/runner/distancia-entre-dois-pontos/main.cs:line 9 中的 String[] args)
Can anyone help?任何人都可以帮忙吗?
Use some LINQ and Extension methods使用一些 LINQ 和扩展方法
static class Program
{
static void Main(string[] args)
{
string text1 = "4376.0 4328.0 14.71 116.7 14.01 0.9912 46.74";
double[] row1 = text1.ParseList();
string text2 = "4376.0,4328.0,14.71,116.7,14.01,0.9912,46.74";
double[] row2 = text2.ParseList(',');
}
}
public static class Extensions
{
public static double[] ParseList(this string text, char token = ' ')
{
return text.Split(token).Select((item) => ParseValue(item)).ToArray();
}
public static double ParseValue(this string text)
{
if (double.TryParse(text.Trim(), out double x))
{
return x;
}
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.