Go語言程式:將字串型別變數轉換為整數


在本教程中,我們將學習如何在 Go 程式語言中將字串型別變數轉換為整數。

此任務需要各種型別的字串轉換,為了執行這些轉換,Go 語言程式中匯入了 “strconv” 包。

可以使用 ParseInt 函式將字串轉換為整數值。它以指定的基數 (0、2 到 36) 和位大小 (0、64) 解碼字串,然後返回等效的結果。

將字串型別變數轉換為整數

語法

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() 方法將字串轉換為整數。

  • 步驟 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() 函式來執行任務並將字串的資料型別轉換為整數。

  • 我們將字串初始化為變數 “string”。

  • 在下一步中,我們列印剛剛宣告的變數的型別。

  • 然後,我們列印該資料型別中的實際值。

  • 然後,我們呼叫 Go 語言 “strconv” 包中的 ParseInt() 函式,並將字串傳遞給該函式。

  • 現在,我們列印了變數的型別,以檢查資料型別是否已從字串更改為整數。

  • 最後,我們使用 fmt.Println() 列印了剛剛從字串資料型別轉換而來的整數的值。

  • 我們已經為不同的值重複了上述步驟,以便更好地理解此函式。

結論

我們已成功編譯並執行了 Go 語言程式程式碼,以將字串型別變數轉換為整數。

更新於:2022年11月14日

瀏覽量:11K+

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.