I was wondering how can I take some numbers in a string and convert them to an integer type? for example if a user entered 12:15pm how can I get 1 and 2 and make an int with value 12?
Given the example above, you could try something like this:
final int value = Integer.parseInt(input.substring(0, input.indexOf(':'))); //value = 12
Where input = 12:15pm
in this case.
Generally speaking, just use a combination of String#indexOf(String)
, String#substring(int, int)
and Integer.parseInt(String)
.
Read the String
and Integer
API's
String.split()
to get the two numeric strings Integer.parseInt(...)
to convert the String to an int. Edit: Using the split() you can do something like:
String time = "12:34pm";
int hour = Integer.parseInt( time.split(":")[0] );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.