What is the best way to extract the integer part of a string like
Hello123
How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.
You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.
As explained before, try using Regular Expressions. This should help out:
String value = "Hello123"; String intValue = value.replaceAll("[^0-9]", ""); // returns 123
And then you just convert that to an int (or Integer) from there.
I believe you can do something like:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+"); int integer = in.nextInt();
EDIT: Added useDelimiter suggestion by Carlos
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