views:

137

answers:

6

I have a string, say "600sp" from which I wish to obtain the integer part (600).

If I do Integer.valueOf("600sp") I get an exception due to the non-numeric value "s" which is encountered in the string.

What is the fastest cleanest way to grab the integer part?

Thanks!

+1  A: 

You can use

Integer.valueOf("0" + "600sp".replaceAll("(\\d*).*", "$1"))

Note:

With this regex you will keep only the initial numbers.


Edit: The "0" + is used to not crash when i have no digits. Tks @jherico!

Topera
This will crash if the string contains no digits.
Jherico
@jherico: tks! I'll fix.
Topera
+3  A: 

Depending on the constraints of your input, you may be best off with regex.

    Pattern p = Pattern.compile("(\\d+)");
    Matcher m = p.matcher("600sp");
    Integer j = null;
    if (m.find()) {
        j = Integer.valueOf(m.group(1));
    }

This regular expression translates as 'give me the set of contiguous digits at the beginning of the string where there is at least 1 digit'. If you have other constraints like parsing real numbers as opposed to integers, then you need to modify the code.

Jherico
+2  A: 

For a shorter and less specific solution, add more context.

StringBuffer numbers = new StringBuffer();
for(char c : "asdf600sp".toCharArray())
{
  if(Character.isDigit(c)) numbers.append(c);
}

System.out.println(numbers.toString());

In the light of the new info, an improved solution:

Integer.valueOf("600sp".replace("sp",""));
Pablo Fernandez
+5  A: 

If your string format is always going to be number followed by some characters, then try this

mystr.split("[a-z]")[0]
Chuk Lee
short and sweet, perfect - thank you.
Brad Hein
cool solution !
stratwine
this will crash if fed an empty string, and can produce invalid results if fed a string with international characters
Jherico
I wrapped it in a try-catch. If the string starts with anything other than a string then there's nothing in it I need. I set the value myself actually in the xml layout (Android app) so I will be careful to always use a numeric value follosed by the units (sp) which is Scaled Pixels in an Android layout.
Brad Hein
Note the first line "If your string format ...". My assumption is that `mystr` would have been checked for errors before reaching this point.
Chuk Lee
+1  A: 

If the string is guaranteed (as you say it is) to be an integer followed by "sp", I would advise against using a more generic regular expression parser, which would also accept other variations (that should be rejected as errors).

Just test if it ends in "sp", an then parse the substring without the last two characters.

Thilo
This is a very good point. Thank you Thilo.
Brad Hein
+1  A: 

I know that this has already been answered, but have you considered java.util.Scanner? It seems to fit the bill perfectly without regex's or other more complex string utilities.

D.Shawley