0

I have a string, which is a list of coordinates, as follows:

st = "((1,2),(2,3),(3,4),(4,5),(2,3))"

I want this to be converted to an array of coordinates,

a[0] = 1,2
a[1] = 2,3
a[2] = 3,4
....

and so on.

I can do it in Python, but I want to do it in Java. So how can I split the string into array in java??

Moid
  • 410
  • 5
  • 9

3 Answers3

6

It can be done fairly easily with regex, capturing (\d+,\d+) and the looping over the matches

String st = "((1,2),(2,3),(3,4),(4,5),(2,3))";

Pattern p = Pattern.compile("\\((\\d+),(\\d+)\\)");
Matcher m = p.matcher(st);
List<String> matches = new ArrayList<>();
while (m.find()) {
    matches.add(m.group(1) + "," + m.group(2));
}
System.out.println(matches);

If you genuinely need an array, this can be converted

String [] array = matches.toArray(new String[matches.size()]);
Adam
  • 35,919
  • 9
  • 100
  • 137
0

Alternative solution:

    String str="((1,2),(2,3),(3,4),(4,5),(2,3))";
    ArrayList<String> arry=new ArrayList<String>();
    for (int x=0; x<=str.length()-1;x++)
    {
        if (str.charAt(x)!='(' && str.charAt(x)!=')' && str.charAt(x)!=',')
        {
            arry.add(str.substring(x, x+3));
            x=x+2;
        }
    }

    for (String valInArry: arry)
    {
        System.out.println(valInArry);
    }

If you don't want to use Pattern-Matcher;

drink-a-Beer
  • 389
  • 1
  • 5
  • 14
0

This should be it:

String st = "((1,2),(2,3),(3,4),(4,5),(2,3))";
String[] array = st.substring(2, st.length() - 2).split("\\),\\(");
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588