Chad Bingham
Chad Bingham

Reputation: 33866

String to int while containing characters

Simple question but I am having trouble. I have an String input that is in this format 12:43. (MM:SS).
I am trying to convert this string in to int (seconds). The only part I don't know how to do is how to get 12 and 43 without getting invalid double error. Because it is containing that ":" in the string, I can't do the usual Parse.parseInt(string); .

Upvotes: 5

Views: 125

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533570

You can do

String s = "12:43";
int secs = (s.charAt(0)-'0')*600 + (s.charAt(1) - '0') * 60 
           + (s.charAt(3)-'0')*10 + s.charAt(4)-'0';

or

int secs = s.charAt(0)*600+s.charAt(1)*60+s.charAt(3)*10+s.charAt(4)-'0'*671;

Upvotes: 5

Maroun
Maroun

Reputation: 95968

  • split the string according to :
  • For each int in the resulting array, apply parseInt

Upvotes: 9

Related Questions