gpt4 book ai didi

go - 检查字符串是否为 int

转载 作者:IT老高 更新时间:2023-10-28 12:58:37 24 4
gpt4 key购买 nike

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

类似

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

注意:我知道 strconv.Atoi 返回错误,但是还有其他函数可以做到这一点吗?

strconv.Atoi 的问题是它会为 "a7"

7 >

最佳答案

正如你所说,你可以使用 strconv.Atoi 来实现这一点。

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

您可以在 ScanInts 模式下使用 scanner.Scanner(来自 text/scanner),或者使用正则表达式来验证字符串,但是Atoi 是适合这项工作的工具。

关于go - 检查字符串是否为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22593259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com