📌  相关文章
📜  如何在 Golang 中将字符串转换为整数类型?

📅  最后修改于: 2021-10-24 13:05:15             🧑  作者: Mango

Golang 中的字符串是一系列宽度可变的字符,其中每个字符都使用 UTF-8 编码由一个或多个字节表示。在 Go 语言中,有符号和无符号整数都有四种不同的大小。为了在 Golang 中将字符串转换为整数类型,可以使用以下方法。

1. Atoi()函数: Atoi 代表ASCII to integer,返回ParseInt(s, 10, 0) 转换为int 类型的结果。

句法:

func Atoi(s string) (int, error)

例子:

// Go program to illustrate how to
// Convert string to the integer type
  
package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    str1 := "123"
  
    // using ParseInt method
    int1, err := strconv.ParseInt(str1, 6, 12)
  
    fmt.Println(int1)
  
    // If the input string contans the integer
    // greater than base, get the zero value in return
    str2 := "123"
  
    int2, err := strconv.ParseInt(str2, 2, 32)
    fmt.Println(int2, err)
  
}

输出:

123
0 strconv.Atoi: parsing "12.3": invalid syntax

2. ParseInt()函数: ParseInt 在给定的基数(0、2 到 36)和位大小(0 到 64)中解释字符串s,并返回相应的值 i。

句法:

func ParseInt(s string, base int, bitSize int) (i int64, err error)

例子:

// Go program to illustrate how to
// Convert string to the integer type
  
package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    str1 := "123"
  
    // using ParseInt method
    int1, err := strconv.ParseInt(str1, 6, 12)
  
    fmt.Println(int1)
  
    // If the input string contans the integer
    // greater than base, get the zero value in return
    str2 := "123"
  
    int2, err := strconv.ParseInt(str2, 2, 32)
    fmt.Println(int2, err)
  
}

输出:

51
0 strconv.ParseInt: parsing "123": invalid syntax