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!
If your string format is always going to be number followed by some characters, then try this
mystr.split("[a-z]")[0]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With