How can I find int values within a string

11,958

Solution 1

You can use a regex first:

String s = "ksl13 m4n";
String clean = s.replaceAll("\\D+",""); //remove non-digits

Then you can use Integer.parseInt:

int i = Integer.parseInt(clean);

and i will be 134.

Solution 2

If you don't want to use a regex, you can do something like this:

private String buildNumber(String str) {
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if(Character.isDigit(ch)) 
            strBuilder.append(ch);
    }
    return strBuilder.toString();
}

Then you can turn it to an int using Integer#parseInt.

See StringBuilder and Character for additional information.

Solution 3

String str = "ksl13 m4n";
String strArray[] = str.split("\D+"); will give you the array of integer values

Share:
11,958
Fraser Price
Author by

Fraser Price

Updated on June 28, 2022

Comments

  • Fraser Price
    Fraser Price almost 2 years

    I have a string, e.g. "ksl13<br>m4n", and I want to remove all non-digit characters in order to get the int 134.

    Integer.parseInt(s) obviously isn't going to work, but not sure how else to go about it.