Reputation: 891
I'm trying to get the 5th, 6th and 7th digits from a list of digits.
E.g. I want to get the year out of the variable dateofbirth
, and save it as a separate variable called dob
, as an int
.
Here is what I have:
int dateofbirth = 17031989
String s = Integer.toString(dateofbirth);
int dob = s.charAt(5);
What would I have to put in the parentheses after s.charAt
to get a few digits in a row?
Upvotes: 2
Views: 19319
Reputation: 5032
You want to use String.substring (untested):
int dateofbirth = 17031989;
String s = Integer.toString(dateofbirth);
String year = s.substring(4, 8);
int yearInt = Integer.parseInt(year);
Upvotes: 2
Reputation: 12212
If you are handling dates, you could use SimpleDateFormat and Calendar to pull out the year:
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(formatter.parse(Integer.toString(dateofbirth)));
int year = cal.get(Calendar.YEAR);
Upvotes: 1
Reputation: 19270
s.substring(5)
will give you everything starting from index 5
. You could also give a second argument to indicate where you want the substring to end.
Upvotes: 2
Reputation: 8988
This approach won't work for several reasons:
If you want to extract 1989 from this string you should use substring and then convert this string into an Integer using Integer.valueOf()
Upvotes: 0
Reputation: 1415
Check out String.substring() !
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int%29
Upvotes: 0
Reputation: 306
you do:
String s = String.valueOf(dateofbirth);
int yourInt = Integer.parseInt(s.substring(startIndex,length))
Upvotes: 0
Reputation: 72284
No need for the string conversion:
int dateofbirth = 17031989;
System.out.println(dateofbirth%10000); //1989
If you did want to do it as a string, then the substring() method would be your friend. You'd also need to use Integer.parseInt()
to convert the string back into an integer. Taking a character value as an integer will give you the ASCII value of that character, not an integer representing that character!
Upvotes: 6