-1

I'm having a string containing coordinates like this:

String coord="-7.21548 1.25434,2.1648 0.154654,..."

Where the first double represents x-coordinates, while the second is the y-coordinates. The coordinates are separated by a white space and points with a comma. How can I get those points coordinates in Java?

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
  • 2
    Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – jhamon Apr 17 '18 at 18:14
  • 1
    Its been asked many times here and it has answer at this community. Its better you [search](https://stackoverflow.com/search) your question or at least review the similar questions drop down as you type your question. You'd better consult [this page](https://stackoverflow.com/help/how-to-ask) to learn how you can ask better questions which will be answered quickly. For this particular case, take a look at the page @jhamon mentioned – behkod Apr 17 '18 at 18:24

1 Answers1

2

You could try:

String[] points = coord.split("\\s*[,]\\s*");

Where the split() method returns an array of Strings.

Explanation -

\\s*   ->  Indicates zero-or-more spaces
[,]    ->  Indicates a comma (which is basically that one present between the points)
\\s*   ->  Indicates that there may be zero-or-more spaces between the comma and the next point

However, if your text may contain some words, then you would be better off using the Pattern and Matcher class by importing the java.util.regex package:

String coords = "Hi there! 2.3 12.6786, -1234 7.3, 34 35, are the points!";

Pattern p = Pattern.compile("[0-9\\-][0-9 .\\-]+(?=,)");
Matcher m = p.matcher(coords);

while(m.find())
    System.out.println("Point found = '" + m.group(0) + "'");

Which gives the output of:

Point found = '2.3 12.6786'
Point found = '-1234 7.3'
Point found = '34 35'

Where m.group(0) contains the complete match (point) found.

Note - The above method works perfectly only if the last point's coordinates are followed by a comma, otherwise it will match the points upto, but not including, the last one.

Community
  • 1
  • 1
Robo Mop
  • 3,485
  • 1
  • 10
  • 23
  • Thank you @Coffeehouse for your answer, it works fine – Oussama DJIDJ Apr 18 '18 at 09:54
  • @OussamaDJIDJ If you feel that an answer has satisfactorily solved your problem, consider marking it as helpful, and even upvote it! This would certainly aid any future references :) – Robo Mop Apr 19 '18 at 01:55