Java's String series--judging whether a string is a number

Original URL: String Series of Java--Judging whether a string is a number

Introduction

This article introduces the method of Java to determine whether a string is a number.

Method 1: single character judgment

public static boolean checkIsNumeric(String str) {
    String tmpStr = str;

    // 判断负数
    if (str.startsWith("-")) {
        tmpStr = str.substring(1);
    }

    for (int i = tmpStr.length(); --i >= 0; ) {
        if (!Character.isDigit(tmpStr.charAt(i))) {
            return false;
        }
    }
    return true;
}

Method 2: Regular Expressions

// import java.util.regex.Pattern;

public static boolean checkIsNumeric(String str) {
    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
    return pattern.matcher(str).matches();
}

Method 3: parse method for integers

public static boolean checkIsNumeric(String str) {
    try {
        Integer.parseInt(str);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

Method 4: Ascii code

public static boolean checkIsNumeric(String str) {
    String tmpStr = str;

    // 判断负数
    if (str.startsWith("-")) {
        tmpStr = str.substring(1);
    }

    for (int i = tmpStr.length(); --i >= 0; ) {
        int chr = tmpStr.charAt(i);
        if (chr < 48 || chr > 57)
            return false;
    }
    return true;
}

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/128188835