Best way to get integer part of the string "600sp"?

11,099

Solution 1

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

mystr.split("[a-z]")[0]

Solution 2

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.

Solution 3

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",""));

Solution 4

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!

Solution 5

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.

Share:
11,099
Brad Hein
Author by

Brad Hein

Professional Linux Engineer Recreational Software Engineer. Some of my Apps (also see my home page: www.gtosoft.com): Sleuth Open Source vehicle network deep diagnostic tool libVoyager Open Source Java to vehicle link VoyagerDash advanced vehicle controls and diagnostics VoyagerConnect advanced vehicle diagnostics VoyagerRC Research app for remotely controlling vehicle systems. Lactoid food journal

Updated on July 15, 2022

Comments

  • Brad Hein
    Brad Hein almost 2 years

    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!