How can I get multiple characters from a string?
I'm trying to get the 开发者_StackOverflow中文版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?
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!
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.
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);
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);
you do:
String s = String.valueOf(dateofbirth);
int yourInt = Integer.parseInt(s.substring(startIndex,length))
Check out String.substring() !
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int%29
This approach won't work for several reasons:
- s.charAt(5) will give you the ASCII code of the 6th character (which is not 9).
- There is no method to get several chars
If you want to extract 1989 from this string you should use substring and then convert this string into an Integer using Integer.valueOf()
Integer.parseInt(s.subString(4))
From the JRE documentation: getChars
精彩评论