java get number out of string code example

Example 1: java get number out of string

for(int i=0; i<yourString.length();i++) {
  if(Character.isDigit(yourString.charAt(i))) {
    // Do something with the number
    // For example convert it to int:
    int yourNumber = Integer.parseInt(String.valueOf(yourString.charAt(i)));
  }
}

Example 2: java get number at the end of string

public static BigInteger lastBigInteger(String s) {
    int i = s.length();
    while (i > 0 && Character.isDigit(s.charAt(i - 1))) {
        i--;
    }
    return new BigInteger(s.substring(i));
}

Tags:

Java Example