The sword refers to the second edition of the offer interview question 20: Strings representing numerical values (java)

Topic description:
Please implement a function to determine whether a string represents a numeric value (including integers and decimals). For example, the strings "+100", "5e2", "-123", "3.1416" and "-1E-16" all represent numeric values. But neither "12e", "1a3.14", "1.2.3", "+-5" nor "12e+4.3".

Analysis:
1. There may be a positive or negative '-' or '+' before the value. Next is a number of digits from 0 to 9 that represent the integer part of the value (in some decimals there may be no integer part of the value). If the value is a decimal, there may be several digits from 0 to 9 after the decimal point to represent the fractional part of the value. If the value is expressed in scientific notation, it is followed by an 'e' or 'E', followed by an integer (which may have a sign) for the exponent.
2. When judging whether a string conforms to the above pattern, first check whether the first character is a plus or minus sign. If so, move one character over the string and continue scanning the remaining strings for digits 0 to 9. If it is a decimal, the decimal point will be encountered. In addition, if the value is expressed in scientific notation, it is possible to encounter 'e' or 'E' after an integer or decimal.

code show as below:

/**
 * 表示数值的字符串
 *  数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,其中A和C都是整数(可以有正负号也可以没有),而B是一个无符号整数
 */
public class NumberString {

    int index;

    public boolean isNumber(char[] str){
        if(str == null || str.length == 0){
            return false;
        }

        index = 0;
        boolean flag =  scanInteger(str);
        //判断小数部分
        if(index < str.length && str[index] == '.'){
            index++;
            flag = scanUnsignedInteger(str) || flag;
        }
        //判断指数部分
        if(index < str.length && (str[index] == 'e' || str[index] == 'E')){
            index++;
            flag = scanInteger(str) && flag;
        }
        return index >= str.length && flag;
    }

    //扫描整数部分
    public boolean scanInteger(char[] str){
        if(index < str.length && (str[index] == '+' || str[index] == '-')){
            index++;
        }
        return scanUnsignedInteger(str);
    }

    //扫描无符号整数部分
    public boolean scanUnsignedInteger(char[] str){
        int temp = index;
        while(index < str.length && str[index] >= '0' && str[index] <= '9'){
            index++;
        }
        return index > temp;
    }



    public static void main(String[] args) {
        NumberString test = new NumberString();
        String str = "12e+5.4";
        boolean result = test.isNumber(str.toCharArray());
        System.out.println(result);
    }
}

You can also use regular expressions:

public static  boolean isNumeric(String str) {
        return str.matches("[\\+-]?[0-9]*(\\.[0-9]*)?([eE][\\+-]?[0-9]+)?");
    }

Or use the exception way in java:

public static boolean isNumeric(String str) {
        try {
            double res = Double.parseDouble(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609009&siteId=291194637