Reputation: 440
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??
Upvotes: 0
Views: 109
Reputation: 298898
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("\\),\\(");
Upvotes: 0
Reputation: 397
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;
Upvotes: 0
Reputation: 36703
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()]);
Upvotes: 6