将格式化的字符串解析为数组

时间:2018-08-08 22:40:53

标签: java

我正在使用一个InputSteam来接收这种格式的字符串。

[[1,3,4],[43,6,3],[4,2,5]]

我如何将其解析为可用的java数组?

2 个答案:

答案 0 :(得分:4)

这是一种无需使用第三方库即可解析该文本的方法。

public static int[][] parse(String text) {
    if (! text.startsWith("[[") || ! text.endsWith("]]"))
        throw new IllegalArgumentException("Invalid text: " + text);
    String[] subTexts = text.substring(2, text.length() - 2).split("\\],\\[");
    int[][] result = new int[subTexts.length][];
    for (int i = 0; i < subTexts.length; i++) {
        String[] valueTexts = subTexts[i].split(",");
        result[i] = new int[valueTexts.length];
        for (int j = 0; j < valueTexts.length; j++)
            result[i][j] = Integer.parseInt(valueTexts[j]);
    }
    return result;
}

测试

System.out.println(Arrays.deepToString(parse("[[1,3,4],[43,6,3],[4,2,5]]")));

输出

[[1, 3, 4], [43, 6, 3], [4, 2, 5]]

答案 1 :(得分:1)

这是我的尝试(虽然有点冗长)。程序分别使用以下三个输入字符串创建了int[][]-分别尝试时:

"[[1,3,4],[43,6,3],[4,2,5]]"
"[[]]"
"[[],[1,2,3],[0]]"

程序代码:

import java.util.*;
import java.util.stream.*;
public class ArrayParsing {
    private final static String input = "[[1,3,4],[43,6,3],[4,2,5]]";
    private final static String open = "[";
    private final static String open2 = "[[";
    private final static String close = "]";
    private final static String close2 = "]]";
    private final static List<int []> outerContent = new ArrayList<>();
    public static void main(String [] args) {
        String content = "";
        String token = "";
        boolean flag = false;
        for (int i = 0; i < input.length(); i++) {
            token = input.substring(i, i+1);
            if (token.equals(open) || token.equals(open2)) {
                content = "";
                flag = false;
            }
            else if (token.equals(close) && !flag) {
                buildArray(content);
                flag = true;
            }
            else {
                content = content.concat(token);
            }
        }
        int [][] result = outerContent.toArray(new int[outerContent.size()][]);
        System.out.println(Arrays.deepToString(result));
    }
    private static void buildArray(String in) {
        int [] intArray = new int[0];   
        if (in.trim().length() > 0) {
            String [] elements = in.split(",");
            intArray = Arrays.stream(elements)
                             .mapToInt(s -> Integer.parseInt(s))
                             .toArray();
        }
        outerContent.add(intArray);
    }
}