Skip to content
Advertisement

Find certain numbers in a String and add them in separate ints

I need a way to take specific “random” numbers from a string and put them each in separate int variables. For example this string cannot/shouldnt be changed: String date = "59598 22-01-19 22:46:32 00 0 0 66.2 UTC(NIST) * ";

I need these three numbers in separet ints “22-01-19”. So one int would be called “day” and it holds the number 19, another int is called “month” and it holds the number 1, another int called “year” and it holds the number 22.

This is what it would look like:

String date = "59598 22-01-19 22:46:32 00 0 0  66.2 UTC(NIST) * ";
int day = 0;
int month = 0;
int year = 0;

//(method for finding these numbers and putting them into the separate int variables)

System.out.println(year+" "+month+" "+day);

Thank you in advance!

Note: I did not find a solution that explained this well enough for me to understand it, I apologize if there already excists a duplicate of this question.

Advertisement

Answer

You could split date twice to get a list of the date

String date = "59598 22-01-19 22:46:32 00 0 0  66.2 UTC(NIST) * ";
String[] splittedDate = date.split(" ")[1].split("-");

int day = Integer.valueOf(splittedDate[2]);
int month = Integer.valueOf(splittedDate[1]);
int year = Integer.valueOf(splittedDate[0]);

//(method for finding these numbers and putting them into the separate int variables)

System.out.println(year+" "+month+" "+day);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement