string 在 Go 中将字符串转换为整数类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4278430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to integer type in Go?
提问by Matt Joiner
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?
我试图从返回的字符串转换flag.Arg(n)
成int
。在 Go 中执行此操作的惯用方法是什么?
回答by peterSO
For example,
例如,
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
func main() {
flag.Parse()
s := flag.Arg(0)
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
fmt.Println(s, i)
}
回答by icza
Converting Simple strings
转换简单字符串
The easiest way is to use the strconv.Atoi()
function.
最简单的方法是使用strconv.Atoi()
函数。
Note that there are many other ways. For example fmt.Sscan()
and strconv.ParseInt()
which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi()
:
请注意,还有许多其他方法。例如fmt.Sscan()
,strconv.ParseInt()
它提供了更大的灵活性,因为您可以指定 base 和 bitsize。也如文档中所述strconv.Atoi()
:
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
Atoi 等价于 ParseInt(s, 10, 0),转换为 int 类型。
Here's an example using the mentioned functions (try it on the Go Playground):
这是使用上述函数的示例(在Go Playground上尝试):
flag.Parse()
s := flag.Arg(0)
if i, err := strconv.Atoi(s); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
var i int
if _, err := fmt.Sscan(s, &i); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
Output (if called with argument "123"
):
输出(如果使用参数调用"123"
):
i=123, type: int
i=123, type: int64
i=123, type: int
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 input string
.
还有一个方便的方法fmt.Sscanf()
,它提供了更大的灵活性,因为格式字符串可以指定数字格式(如宽度、基数等)以及输入中的其他额外字符string
。
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:
这对于解析包含数字的自定义字符串非常有用。例如,如果您的输入以"id:00123"
您有前缀的形式提供,"id:"
并且数字固定为 5 位数字,如果较短则用零填充,这很容易解析,如下所示:
s := "id:00123"
var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
fmt.Println(i) // Outputs 123
}
回答by maerics
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 flexible
strconv.ParseInt(...)
最快的strconv.Atoi(...)
还是很快fmt.Sscanf(...)
不是特别快,但最灵活
Here's a benchmark that shows usage and example timing for each function:
这是一个基准,显示每个函数的用法和示例时间:
package main
import "fmt"
import "strconv"
import "testing"
var num = 123456
var numstr = "123456"
func BenchmarkStrconvParseInt(b *testing.B) {
num64 := int64(num)
for i := 0; i < b.N; i++ {
x, err := strconv.ParseInt(numstr, 10, 64)
if x != num64 || err != nil {
b.Error(err)
}
}
}
func BenchmarkAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
x, err := strconv.Atoi(numstr)
if x != num || err != nil {
b.Error(err)
}
}
}
func BenchmarkFmtSscan(b *testing.B) {
for i := 0; i < b.N; i++ {
var x int
n, err := fmt.Sscanf(numstr, "%d", &x)
if n != 1 || x != num || err != nil {
b.Error(err)
}
}
}
You can run it by saving as atoi_test.go
and running go test -bench=. atoi_test.go
.
您可以通过另存为atoi_test.go
并运行来运行它go test -bench=. atoi_test.go
。
goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8 100000000 17.1 ns/op
BenchmarkAtoi-8 100000000 19.4 ns/op
BenchmarkFmtSscan-8 2000000 693 ns/op
PASS
ok command-line-arguments 5.797s
回答by MD.Mahedi hasan
Try this
尝试这个
import ("strconv")
value : = "123"
number,err := strconv.ParseUint(value, 10, 32)
回答by Jenyokcoder
If you control the input data, you can use the mini version
如果你控制输入数据,你可以使用迷你版
package main
import (
"testing"
"strconv"
)
func Atoi (s string) int {
var (
n uint64
i int
v byte
)
for ; i < len(s); i++ {
d := s[i]
if '0' <= d && d <= '9' {
v = d - '0'
} else if 'a' <= d && d <= 'z' {
v = d - 'a' + 10
} else if 'A' <= d && d <= 'Z' {
v = d - 'A' + 10
} else {
n = 0; break
}
n *= uint64(10)
n += uint64(v)
}
return int(n)
}
func BenchmarkAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
in := Atoi("9999")
_ = in
}
}
func BenchmarkStrconvAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
in, _ := strconv.Atoi("9999")
_ = in
}
}
the fastest option (write your check if necessary). Result :
最快的选择(如有必要,请写支票)。结果 :
Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2 100000000 14.6 ns/op
BenchmarkStrconvAtoi-2 30000000 51.2 ns/op
PASS
ok path 3.293s