Golang 将字符串类型变量转换为int

Golang 将字符串类型变量转换为int

在本教程中,我们将学习如何在Go编程语言中将字符串类型变量转换为int。

为了执行这个任务,需要各种类型的字符串转换,在Go语言程序中导入了”strconv”包。

可以使用ParseInt函数将字符串转换为整数值。它将字符串解码为指定的基数(0,2到36)和位大小(0,64),然后返回相应的结果。

将字符串类型变量转换为int

语法

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

ParseInt()函数 用于将字符串转换为整数类型值。此函数接受两个参数,一个是要转换的字符串,另一个是整数类型值。该值指定结果的大小。它可以是32位或64位。该函数将最终结果返回为64位整数类型数字和错误,如果在转换过程中出现任何问题,则可以将错误打印在屏幕上。如果我们希望以32位浮点数形式获得结果,则必须将位大小指定为32,这使得结果可转换为32位浮点数。

步骤

  • 步骤1 − 导入包 fmt、reflect和strconv

  • 步骤2 − 开始函数 main()

  • 步骤3 − 声明字符串’字符串’

  • 步骤4 − 使用 reflect.TypeOf() 函数显示变量的类型。

  • 步骤5 − 使用 ParseInt() 方法将字符串转换为整型。

  • 步骤6 − 使用 fmt.Println() 函数打印整数类型和整数值。

示例

package main
// import the required packages to perform the task
import (
   "fmt"
   "reflect"
   "strconv"
)

// fmt package allows us to print anything on the screen
// reflect package allows us to get the format of a data type
// strconv package allows us to use other pre-defined function
// call the main function
func main() {

   // initialize the srting
   string := "tutorialspoint"

   // print the type of variable
   fmt.Println("Type of variable Before conversion is :", reflect.TypeOf(string))

   // print the value of string
   fmt.Println("String value is:", string)

   // use the ParseInt() Function
   x, _ := strconv.ParseInt(string, 10, 64)

   // print the type of variable
   fmt.Println("Type of variable After conversion is :", reflect.TypeOf(x))

   // print the value
   fmt.Println("Integer value is:", x, "\n")

   // initialize the other srting
   string1 := "100"

   // print the type of variable
   fmt.Println("Type of variable Before conversion is :", reflect.TypeOf(string1))

   // print the value of string
   fmt.Println("String value is:", string1)

   // use the ParseInt() Function on string
   y, _ := strconv.ParseInt(string1, 10, 64)

   // print the type of variable
   fmt.Println("Type of variable After conversion is :", reflect.TypeOf(y))

   // print tehe value
   fmt.Println("Integer value is: ", y, "\n")
}

输出

Type of variable Before conversion is: string 
String value is: tutorialspoint 
Type of variable After conversion is: int64 
Integer value is: 0 

Type of variable Before conversion is: string 
String value is: 100 
Type of variable After conversion is: int64 
Integer value is: 100

代码说明

  • 首先,我们导入了 fmt、reflect、strconv 这三个包,其中 reflect 包用于打印变量的类型,strconv 包用于进行数据类型转换。

  • 然后我们开始 main() 函数来执行任务并将字符串的数据类型转换为 int。

  • 我们将字符串初始化为一个变量 “string”。

  • 在下一步中,我们打印刚刚声明的变量的类型。

  • 然后我们打印数据类型中实际的值。

  • 接下来我们调用 go 语言的 “strconv” 包中的 ParseInt() 函数,并将字符串传递给该函数。

  • 现在我们已经打印了变量的类型,以检查数据类型是否已经从字符串变为 int。

  • 最后,我们使用 fmt.Printl() 打印了刚刚从字符串数据类型转换为 int 的值。

  • 我们重复上述步骤来理解这个函数的不同值。

结论

我们已经成功编译并执行了 Golang 程序代码,将字符串类型的变量转换为 int。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程