• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i need to grab a Sting like this: "1-25" or one like this "3 selected" and parse it into an int.

 
Marcelo Bordolli
Ranch Hand
Posts: 46
Android Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i need to grab a Sting like this: "1-25" or one like this "3 selected" and parse it into an int. just the numbers like for the first i need an int = 1 25 or similar; and for the second int = 3;

I've tried doing:

Integer foo = Integer.parseInt("3 selected");

but of course its not working

Can someone advise thanks!!
 
Paweł Baczyński
Bartender
Posts: 1764
33
Firefox Browser IntelliJ IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This prints 125. But is it what you want? Do you want just to remove all non-number characers or do you want to get 1 and 25 separately from that String?
 
Henry Wong
author
Marshal
Pie
Posts: 21024
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcelo Bordolli wrote:i need to grab a Sting like this: "1-25" or one like this "3 selected" and parse it into an int. just the numbers like for the first i need an int = 1 25 or similar; and for the second int = 3;

I've tried doing:

Integer foo = Integer.parseInt("3 selected");

but of course its not working

Can someone advise thanks!!



Basically, the easiest way to find numbers in a string is to use regular expressions... see the java.util.regex.Pattern class. Unfortunately, if you don't know regular expressions, it is probably not a good idea to use it -- although, I do highly recommend that you learn it.

Without regular expression, you can loop through the string looking for the characters (that are digits), and then use the substring() method to extract the numbers to be parsed into a int.

Henry
 
Marcelo Bordolli
Ranch Hand
Posts: 46
Android Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks man that would do!!
 
Marcelo Bordolli
Ranch Hand
Posts: 46
Android Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
Winston Gutkowski
Bartender
Pie
Posts: 10277
60
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcelo Bordolli wrote:Thanks man that would do!!

Do be careful though. Remember: "-25" is a perfectly valid number.

Winston
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way is to use a Scanner.You wll suffer an InputMismatchException if your String does not start with a valid int.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic