java – Extracting numbers from a String

Question:

I have a String in the following format:

01 - 02 - 03 - 04 - 45 - 86

I need to put these numbers into an array int[6] . What is the best way to do this operation?

Answer:

You can do like this:

public class Test {
    public static void main(String[] args) {
        String s = "01 - 02 - 03 - 04 - 45 - 86";
        String[] sp = s.split(" - ");
        int n[] = new int[sp.length];

        for (int i = 0; i < sp.length; i++) {
            n[i] = Integer.parseInt(sp[i]);
        }
        for (int i = 0; i < sp.length; i++) {
            System.out.println(" " + n[i]);
        }
    }
}

You can see the documentation here.

Scroll to Top