Java : spliting a string into integers


Keywords:java 


Question: 

I have this string 10-12-1999 and I want to store the values into a different variables like this:

So I have this string data= 10-12-1999 and I want to store it like this

int day =10;
int month = 12;
int year = 1999;

Can anyone point me into the right direction?


2 Answers: 

You need to use the public String[] split(String regex) method available in the String class :

I hope this helps :-

String date="10-12-1999";
String [] s1=date.split("-");
int day=Integer.parseInt(s1[0]);
int month=Integer.parseInt(s1[1]);
int year=Integer.parseInt(s1[2]);
System.out.println("Day->"+day+"    Month->"+month+"    Year->"+year); 

This will help extracting out all the date elements and you can assign them to all the requisite variables!

 
String data = "10-12-1999"
String[] dataArray = data.split("-");
int day = Integer.parseInt(dataArray[0])
int month = Integer.parseInt(dataArray[1])
int year = Integer.parseInt(dataArray[2])