简体   繁体   中英

converts parts of a string to int in java

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

  1. You can use the String.split() to get the two numeric strings
  2. You can use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM