将字符串值转换为double类型的2d数组 [英] Turn string values into 2d array of type double

查看:110
本文介绍了将字符串值转换为double类型的2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

String stringProfile = "0,4.28 10,4.93 20,3.75";

我试图把它变成一个如下数组:

I am trying to turn it into an array like as follows:

double [][] values = {{0, 4.28}, {10, 4.93}, {20, 3.75}};

我已经格式化了字符串以删除任何空格并用逗号替换:

I've formatted the string to remove any whitespace and replace with a comma:

String stringProfileFormatted = stringProfile.replaceAll(" ", ",");

所以现在String stringProfileFormatted =0,4.28,10,4.93,20 ,3.75;

So now String stringProfileFormatted = "0,4.28,10,4.93,20,3.75";

然后创建一个String数组:

I then create a String array:

String[] array = stringProfileFormatted.split("(?<!\\G\\d+),");

因此,对于数组中的每个元素,每2个逗号值为字符串。

So for every element in the Array is every 2 commas worth of string.

不知道如何转换成2d数组。这甚至是正确的方法吗?

Not sure how to then convert into a 2d array. Is this even the right way to go about it?

推荐答案

我会一步一步地解决这个问题。

I would go step by step resolving this task.

首先,我将原始 String 拆分为空格,
然后用逗号分割结果,然后创建一个 double 的数组,其中包含 Double.parseDouble(String value)

First, I would split the original String by a space, then split the results by comma each and afterwards create an array of double out of those values with Double.parseDouble(String value).

public static void main(String[] args) {
    String stringProfile = "0,4.28 10,4.93 20,3.75";

    // split it once by space
    String[] parts = stringProfile.split(" ");

    // create some result array with the amount of double pairs as its dimension
    double[][] results = new double[parts.length][];

    // iterate over the result of the first splitting
    for (int i = 0; i < parts.length; i++) {
        // split each one again, this time by comma
        String[] values = parts[i].split(",");

        // create two doubles out of the single Strings
        double a = Double.parseDouble(values[0]);
        double b = Double.parseDouble(values[1]);

        // add them to an array
        double[] value = {a, b};

        // add the array to the array of arrays
        results[i] = value;
    }

    // then print the result
    for (double[] pair : results) {
        System.out.println(String.format("%.0f and %.2f", pair[0], pair[1]));
    }
}

是的,这些是很多行代码,但很可能比lambda表达式更容易理解(在我看来,它更酷,更优雅)。

Yes, these are a lot of lines of code, but most likely more easily understandable than lambda expressions (which are cooler and more elegant in my opinion).

这篇关于将字符串值转换为double类型的2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆