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步 – 声明字符串’string
-
第4步 – 使用 reflect.typeof() 函数显示变量的类型。
-
第5步 – 使用 ParseInt() 方法将字符串转换为Int。
-
第6步 – 使用 fmt.Println() 函数打印Integer类型和整数值。
例子
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。
-
我们将字符串初始化为一个var “string”。
-
在接下来的步骤中,我们要打印我们刚刚声明的变量的类型。
-
然后我们打印数据类型中的实际值。
-
然后我们从go语言的 “strconv “包中调用 ParseInt() 函数,并将字符串传递给该函数。
-
现在我们已经打印了变量的类型,以检查数据类型是否从字符串变成了Int。
-
最后,我们用fmt.Printl()打印了我们刚刚从字符串数据类型转换过来的Int值。
-
我们对不同的值重复了上述步骤,以便更好地理解这个函数。
总结
我们已经成功地编译并执行了Golang程序代码,将字符串类型的变量转换为Int。