简体   繁体   中英

Java: String to integer array

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

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()]);

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM