Go 中将字符串转换为整数类型?
我正在尝试将从 flag.Arg(n)
返回的字符串转换为 int
。在 Go 中执行此操作的惯用方法是什么?
I'm trying to convert a string returned from flag.Arg(n)
to an int
. What is the idiomatic way to do this in Go?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您控制输入数据,您可以使用
最快的迷你版本选项(如有必要,请写下您的支票)。结果 :
If you control the input data, you can use the mini version
the fastest option (write your check if necessary). Result :
例如
strconv.Atoi
。代码:
For example
strconv.Atoi
.Code:
转换简单字符串
最简单的方法是使用
strconv.Atoi()
函数。请注意,还有许多其他方法。例如
fmt.Sscan()
和strconv.ParseInt()
这提供了更大的灵活性,因为您可以指定基址和位大小例子。另如strconv.Atoi()
的文档中所述:这是使用上述函数的示例(在 Go Playground 上尝试):
输出(如果使用参数
"123"
):解析自定义字符串
还有一个方便的
fmt.Sscanf()
提供了更大的灵活性,就像格式字符串一样,您可以指定数字格式(如宽度、基数等)以及输入string< 中的其他额外字符/代码>。
这对于解析包含数字的自定义字符串非常有用。例如,如果您的输入以
"id:00123"
的形式提供,其中有前缀"id:"
并且数字固定为 5 位数字,并用零填充如果更短,这很容易解析,如下所示:Converting Simple strings
The easiest way is to use the
strconv.Atoi()
function.Note that there are many other ways. For example
fmt.Sscan()
andstrconv.ParseInt()
which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation ofstrconv.Atoi()
:Here's an example using the mentioned functions (try it on the Go Playground):
Output (if called with argument
"123"
):Parsing Custom strings
There is also a handy
fmt.Sscanf()
which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the inputstring
.This is great for parsing custom strings holding a number. For example if your input is provided in a form of
"id:00123"
where you have a prefix"id:"
and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:以下是将字符串解析为整数的三种方法,从最快的运行时间到最慢的运行时间:
strconv.ParseInt(. ..)
最快strconv.Atoi(...)< /code>
还是很快
fmt.Sscanf(...)
不是非常快,但最灵活这是一个基准测试,显示每个函数的用法和示例计时:
您可以通过另存为
atoi_test.go
并运行go test -bench 来运行它=。 atoi_test.go
。Here are three ways to parse strings into integers, from fastest runtime to slowest:
strconv.ParseInt(...)
fasteststrconv.Atoi(...)
still very fastfmt.Sscanf(...)
not terribly fast but most flexibleHere's a benchmark that shows usage and example timing for each function:
You can run it by saving as
atoi_test.go
and runninggo test -bench=. atoi_test.go
.试试这个
Try this