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??

6
  • 2
    Possible duplicate of How to split a string in Java Commented Mar 14, 2017 at 13:05
  • 1
    split("),(") and remove the remaining parenthesis? Commented Mar 14, 2017 at 13:05
  • 'split("),(")' may work, but the first and last element have extra parenthesis with them. Commented Mar 14, 2017 at 13:07
  • @MoidShaikh Than replace the first and last paranthesis if it´s not needed here Commented Mar 14, 2017 at 13:08
  • How to split a string in Java this is different. In my string, there is extra parenthesis. It's a list of coordinates. Commented Mar 14, 2017 at 13:09

3 Answers 3

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()]);
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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("\\),\\(");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.