Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
user2704743 Avatar asked Nov 18 '25 16:11

user2704743


2 Answers

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).

like image 67
Josh M Avatar answered Nov 20 '25 05:11

Josh M


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] );
like image 42
camickr Avatar answered Nov 20 '25 05:11

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!