如何在Golang中检查字符串值是否为整数?
就像是
v := "4"
if isInt(v) {
fmt.Println("We have an int, we can safely cast this with strconv")
}
Run Code Online (Sandbox Code Playgroud)
注意:我知道strconv.Atoi
返回错误,但还有其他功能吗?
的问题strconv.Atoi
是,它会返回7
的"a7"
Pau*_*kin 115
如你所说,你可以使用strconv.Atoi.
if _, err := strconv.Atoi(v); err == nil {
fmt.Printf("%q looks like a number.\n", v)
}
Run Code Online (Sandbox Code Playgroud)
您可以在模式下使用scanner.Scanner
(from text/scanner
)ScanInts
,或使用正则表达式来验证字符串,但Atoi
它是正确的工具.
小智 22
这是更好的,你可以检查高达64(或更少)位的int
strconv.Atoi仅支持32位
if _, err := strconv.ParseInt(v,10,64); err == nil {
fmt.Printf("%q looks like a number.\n", v)
}
Run Code Online (Sandbox Code Playgroud)
尝试用v:="12345678900123456789"
您可以使用govalidator
.
govalidator.IsInt("123") // true
Run Code Online (Sandbox Code Playgroud)
package main
import (
"fmt"
valid "github.com/asaskevich/govalidator"
)
func main() {
fmt.Println("Is it a Integer? ", valid.IsInt("978"))
}
Run Code Online (Sandbox Code Playgroud)
输出:
$ go run intcheck.go
Is it a Integer? true
Run Code Online (Sandbox Code Playgroud)
您也可以使用正则表达式来检查这一点。
这可能有点矫枉过正,但如果您想扩展规则,它也为您提供了更大的灵活性。
这里有一些代码示例:
package main
import (
"regexp"
)
var digitCheck = regexp.MustCompile(`^[0-9]+$`)
func main() {
digitCheck.MatchString("1212")
}
Run Code Online (Sandbox Code Playgroud)
如果你想看到它运行:https : //play.golang.org/p/6JmzgUGYN3u
希望能帮助到你 ;)
你可以使用unicode.IsDigit()
:
import "unicode"
func isInt(s string) bool {
for _, c := range s {
if !unicode.IsDigit(c) {
return false
}
}
return true
}
Run Code Online (Sandbox Code Playgroud)