I have a text field where someone can enter a string.
But I need to return an integer using that string.
I know how to convert strings to integers, but how do I separate any letters & punctuation from the string so it leaves only numbers?
I have a text field where someone can enter a string.
But I need to return an integer using that string.
I know how to convert strings to integers, but how do I separate any letters & punctuation from the string so it leaves only numbers?
Try this code:
String str = "a1?2.33/4tyz.7!8x";
str = str.replaceAll("\\D", "");
Now str
will contain "1233478"
Match against regular expression. 0-9
Example has been given before. How to extract numbers from a string and get an array of ints?
You could replace all extra symbols with regular expression ant then call Integer.valueOf()
.
For example:
Integer.valueOf(src.replaceAll("[!0-9]",""));
You need to replace all the values you don't want in your string and then parse the rest as an integer:
String userInput = "Number 42 is the best";
userInput = userInput.replaceAll("[^\\d]", '');
return Integer.parseInt(test); //returns '42'
There is an existing post similar on how to do this here