get Int in the middle of a string - Android java.lang

Android examples for java.lang:Integer

Description

get Int in the middle of a string

Demo Code

import android.text.TextUtils;
import java.util.Arrays;
import java.util.Iterator;

public class Main{

    public static int convertToInt(String str) throws NumberFormatException {
        int s, e;
        for (s = 0; s < str.length(); s++)
            if (Character.isDigit(str.charAt(s)))
                break;
        for (e = str.length(); e > 0; e--)
            if (Character.isDigit(str.charAt(e - 1)))
                break;
        if (e > s) {
            try {
                return Integer.parseInt(str.substring(s, e));
            } catch (NumberFormatException ex) {

                throw new NumberFormatException();
            }/*from w  w w.  jav a 2s. co  m*/
        } else {
            throw new NumberFormatException();
        }
    }

}

Related Tutorials