在Go语言中将字符串转换为整数类型的方法是什么?

huangapple go评论143阅读模式
英文:

Convert string to integer type in 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?

答案1

得分: 527

例如strconv.Atoi

代码:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s := "123"

	// 字符串转整数
	i, err := strconv.Atoi(s)
	if err != nil {
		// ... 处理错误
		panic(err)
	}

	fmt.Println(s, i)
}
英文:

For example strconv.Atoi.

Code:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s := "123"

	// string to int
	i, err := strconv.Atoi(s)
	if err != nil {
		// ... handle error
		panic(err)
	}

	fmt.Println(s, i)
}

答案2

得分: 139

转换简单字符串

最简单的方法是使用strconv.Atoi()函数。

请注意还有许多其他方法。例如fmt.Sscan()strconv.ParseInt(),它们提供了更大的灵活性,因为您可以指定基数和位大小等。正如在strconv.Atoi()的文档中所指出的:

> Atoi等效于ParseInt(s, 10, 0),转换为int类型。

以下是使用上述函数的示例(在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)
}

输出(如果使用参数"123"调用):

i=123, type: int
i=123, type: int64
i=123, type: int

解析自定义字符串

还有一个方便的fmt.Sscanf(),它提供了更大的灵活性,因为您可以使用格式字符串指定数字格式(如宽度、基数等),以及输入字符串中的其他额外字符。

这对于解析包含数字的自定义字符串非常有用。例如,如果您的输入以"id:00123"的形式提供,其中有一个前缀"id:"和固定的5位数字,如果较短则用零填充,可以非常容易地解析如下:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
	fmt.Println(i) // 输出123
}
英文:

Converting Simple strings

The easiest way is to use the strconv.Atoi() function.

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():

> Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here's an example using the mentioned functions (try it on the 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"):

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.

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:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
	fmt.Println(i) // Outputs 123
}

答案3

得分: 56

以下是将字符串解析为整数的三种方法,从运行时间最快到最慢:

  1. strconv.ParseInt(...) 最快
  2. strconv.Atoi(...) 仍然非常快
  3. fmt.Sscanf(...) 不是非常快,但最灵活

下面是一个展示每个函数的用法和示例时间的基准测试:

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)
    }
  }
}

您可以将其保存为atoi_test.go并运行go test -bench=. atoi_test.go来运行它。

<!-- language: lang-txt -->

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
英文:

Here are three ways to parse strings into integers, from fastest runtime to slowest:

  1. strconv.ParseInt(...) fastest
  2. strconv.Atoi(...) still very fast
  3. fmt.Sscanf(...) not terribly fast but most flexible

Here's a benchmark that shows usage and example timing for each function:

package main

import &quot;fmt&quot;
import &quot;strconv&quot;
import &quot;testing&quot;

var num = 123456
var numstr = &quot;123456&quot;

func BenchmarkStrconvParseInt(b *testing.B) {
  num64 := int64(num)
  for i := 0; i &lt; 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 &lt; 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 &lt; b.N; i++ {
    var x int
    n, err := fmt.Sscanf(numstr, &quot;%d&quot;, &amp;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.

<!-- language: lang-txt -->

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

答案4

得分: 8

尝试这样做

import ("strconv")

value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //将 uint64 转换为 int
英文:

Try this

import (&quot;strconv&quot;)

value := &quot;123&quot;
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int

答案5

得分: 2

如果您控制输入数据,您可以使用迷你版本

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
	}	
}

最快的选项(如果需要,请编写您自己的检查)。结果:

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
英文:

If you control the input data, you can use the mini version

package main

import (
	&quot;testing&quot;
	&quot;strconv&quot;
)

func Atoi (s string) int {
  	var (
		n uint64
		i int
		v byte
	)	
	for ; i &lt; len(s); i++ {
  		d := s[i]
		if &#39;0&#39; &lt;= d &amp;&amp; d &lt;= &#39;9&#39; {
			v = d - &#39;0&#39;
		} else if &#39;a&#39; &lt;= d &amp;&amp; d &lt;= &#39;z&#39; {
			v = d - &#39;a&#39; + 10
		} else if &#39;A&#39; &lt;= d &amp;&amp; d &lt;= &#39;Z&#39; {
			v = d - &#39;A&#39; + 10
		} else {
			n = 0; break		
		}
  		n *= uint64(10) 
  		n += uint64(v)
  	}
	return int(n)
}

func BenchmarkAtoi(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		in := Atoi(&quot;9999&quot;)
		_ = in
	}	
}

func BenchmarkStrconvAtoi(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		in, _ := strconv.Atoi(&quot;9999&quot;)
		_ = in
	}	
}

the fastest option (write your check if necessary). Result :

Path&gt;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

huangapple
  • 本文由 发表于 2010年11月25日 23:06:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/4278430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定