以下是修正后的代码:

func isNumber(s string) bool {
    num := 0
    for _, a := range s {
        if a == '+' || a == '-' {
            num++
        }
        if num > 1 {
            return false
        }
    }
    for _, a := range s {
        if a == '.' || a == 'e' || a == 'E' {
            return isDecimal(s) || isScientific(s)
        }
    }
    return isInteger(s)
}

func isDecimal(s string) bool {
    if len(s) == 0 {
        return false
    }
    if s[0] == '+' || s[0] == '-' {
        s = s[1:]
    }
    if len(s) == 0 {
        return false
    }
    hasDot := false
    for i, c := range s {
        if c == '.' {
            if hasDot {
                return false
            }
            hasDot = true
        } else if c < '0' || c > '9' {
            return false
        }
        if i == len(s)-1 && c == '.' {
            return false
        }
    }
    return true
}

func isScientific(s string) bool {
    if len(s) == 0 {
        return false
    }
    if s[0] == '+' || s[0] == '-' {
        s = s[1:]
    }
    if len(s) == 0 {
        return false
    }
    hasE := false
    for i, c := range s {
        if c == 'e' || c == 'E' {
            if hasE {
                return false
            }
            hasE = true
            if i == len(s)-1 {
                return false
            }
            return isInteger(s[i+1:])
        } else if c < '0' || c > '9' {
            return false
        }
    }
    return false
}

func isInteger(s string) bool {
    if len(s) == 0 {
        return false
    }
    if s[0] == '+' || s[0] == '-' {
        s = s[1:]
    }
    if len(s) == 0 {
        return false
    }
    for _, c := range s {
        if c < '0' || c > '9' {
            return false
        }
    }
    return true
}

修正后的代码可以正确判断输入 '123.45e+6' 为 true。

Go语言判断字符串是否为数字的代码优化

原文地址: https://www.cveoy.top/t/topic/pT2v 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录