Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

convert string chars to int

 
Patrick Mallahan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a string of startDate = "2005/05/01" how would I take the 01 from the string and make it an int. I know Convert.ToInt works ............ I think.
 
Jeff Grant
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int temp = Integer.valueOf(startDate.substring(8,9));
 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are actually a lot of ways to parse out those numeric values.

An easy way is to get the value using the substring(int startpos,int endpos) method and then use Integer.parseInt(String value) method upon it. Be aware that a RuntimeException (NumberFormatException) is thrown by the parseInt method. If you do not catch it, it will throw an exception if the String does not hold a valid numeric value.
 
Edwin Keeton
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can convert a String to an int like this:
 
pendse anagha
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to it - ensure that you trim the string prior to making a call to "Integer.parseInt"

Thanks ,
-anagha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic