Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

how to extract points from the string "(1,3),(4,6),(3,6)" using java

i am unable to extracts only the points to matrix array using java and then assign it to matrix a[6][6]. I am trying to use split, but it is not working the way I want. Does anyone have suggestion?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use regex to extract numbers from your String for example :

public static void main(String[] args) {
    String str = "(1,3),(4,6),(3,6)";
    Pattern pat = Pattern.compile("-?\d+");
    Matcher mat = pat.matcher(str);
    List<Integer> list = new ArrayList<>();

    while (mat.find()) {
        list.add(Integer.parseInt(mat.group()));
    }

    System.out.println(list);
}

This will gives you a List of int :

[1, 3, 4, 6, 3, 6]

Then you use this value in your array like you want.

EDIT

...extracts only the points to matrix array using java and then assign it to matrix a[6][6]

Your matrix should be in this format :

v v v v v v
v v v v v v
v v v v v v
v v v v v v
v v v v v v
v v v v v v 

So to do that you have to use :

public static void main(String[] args) {
    String str = "(1,3),(4,6),(3,6)";
    Pattern pat = Pattern.compile("-?\d+");
    Matcher mat = pat.matcher(str);

    int[][] a = new int[6][6];
    int i = 0, j = 0;
    while (mat.find()) {
        if(j == 6){
            i++;
            j = 0;
        }
        a[i][j] = Integer.parseInt(mat.group());
        j++;
    }
    System.out.println(Arrays.deepToString(a));
}

This will give you :

[[1, 3, 4, 6, 3, 6], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...