【问题标题】:Split an "array"-like string [closed]拆分类似“数组”的字符串[关闭]
【发布时间】:2015-06-28 23:26:22
【问题描述】:

我想从类似“数组”的字符串(从文件中)中提取一些数据,即:

PR=[[20,5],[24,11],[24,13]]

另外,我想将数据存储到一个实际的数组中,我的意思是:

int[][] pr = {{20,5},{24,11},{24,13}};

编辑:我可以使用正则表达式或类似的东西吗?

【问题讨论】:

  • 这不是问题,而且您没有提供任何研究工作,因此您的“问题”很快就会被关闭
  • 我尝试使用split() 方法。
  • 正则表达式是个坏主意。 data.split("="); data[1] 是数组本身。编写自己的简单解析器
  • @Toumash:我在发布后添加了问题。
  • 另外,我解析了 "PR=" 之后的所有内容。

标签: java arrays split processing


【解决方案1】:

您可以使用的 JSON 库有很多,请注意您需要创建相应的类和对象才能反序列化 JSON 字符串。

以下演示如何使用 Gson 进行操作:

import com.google.gson.Gson;

class Matrix implements Serializable {
    Integer[][] matrix;
    Matrix(){};

    public static  void main(String[] args) {
        Gson gson = new Gson();
        Matrix matrix = gson.fromJson("{\"matrix\" : [[20,5],[24,11],[24,13]]}", Matrix.class);
        System.out.println("matrix = \n" + matrix);

    }

    public String toString() {
        String res = "";
        if (matrix == null)
            return res;

        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix[0].length; j++) {
                res += matrix[i][j] + ",";
            }
            res += "\n";
        }
        return res;
    }
}

输出

matrix = 
20,5,
24,11,
24,13,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    相关资源
    最近更新 更多