小编典典

检查字符串是否为 int

go

如何在 Go 中检查字符串值是否为整数?

就像是

v := "4"
if isInt(v) {
  fmt.Println("We have an int, we can safely cast this with strconv")
}

注意:我知道这会strconv.Atoi返回错误,但是还有其他函数可以执行此操作吗?


阅读 152

收藏
2021-12-09

共1个答案

小编典典

正如您所说,您可以为此使用 strconv.Atoi 。

if _, err := strconv.Atoi(v); err == nil {
    fmt.Printf("%q looks like a number.\n", v)
}

您可以在 mode 中使用scanner.Scanner(from text/scanner) ScanInts,或者使用正则表达式来验证字符串,但它Atoi是适合该工作的工具。

2021-12-09