溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

go語言如何將整型轉(zhuǎn)為字符串

發(fā)布時間:2022-12-28 11:01:45 來源:億速云 閱讀:127 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“go語言如何將整型轉(zhuǎn)為字符串”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

轉(zhuǎn)換方法:1、用fmt包的Sprintf(),支持格式化變量轉(zhuǎn)為字符串,語法“fmt.Sprintf("%d", num)”;2、用strconv包的Itoa(),支持將int類型轉(zhuǎn)換成字符串,語法“strconv.Itoa(num)”;3、用strconv包的FormatInt(),支持將int64類型轉(zhuǎn)換成字符串,語法“strconv.FormatInt(num,10)”。

在實際開發(fā)中我們往往需要對一些常用的數(shù)據(jù)類型進行轉(zhuǎn)換,如 string、int、int64、float 等數(shù)據(jù)類型之間的轉(zhuǎn)換。

int整數(shù)轉(zhuǎn)字符串

1、fmt.Sprintf

fmt 包應(yīng)該是最常見的了,從剛開始學(xué)習(xí) Golang 就接觸到了,寫 ‘hello, world’ 就得用它。它還支持格式化變量轉(zhuǎn)為字符串。%d 代表十進制整數(shù)。

//Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...interface{}) string

使用示例:

str := fmt.Sprintf("%d", a)

2、strconv.Itoa

Go語言中的 strconv 包為我們提供了字符串和基本數(shù)據(jù)類型之間的轉(zhuǎn)換功能。strconv 包中常用的函數(shù)包括 Atoi()、Itia()、parse 系列函數(shù)、format 系列函數(shù)、append 系列函數(shù)等。

其中Itoa()函數(shù)支持 int 類型轉(zhuǎn)換成字符串

//Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string

使用示例:

func main() {
    num := 100
    str := strconv.Itoa(num)
    fmt.Printf("type:%T value:%#v\n", str, str)
}

運行結(jié)果如下所示:

go語言如何將整型轉(zhuǎn)為字符串

3、strconv.FormatInt

支持 int64 類型轉(zhuǎn)換成字符串
參數(shù) i 是要被轉(zhuǎn)換的整數(shù), base 是進制,例如2進制,支持2到36進制。

//FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a(chǎn)' to ‘z' for digit values >= 10.
func FormatInt(i int64, base int) string

使用示例:

str := strconv.FormatInt(a, 10)

擴展知識:字符串轉(zhuǎn)int整數(shù)

1、strconv.Atoi

比較常見的方法

// Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
func Atoi(s string) (int, error)

使用示例:

i,err := strconv.Atoi(a)

2、strconv.ParseInt

功能非常強大

// ParseInt interprets a string s in the given base (0, 2 to 36) and
// bit size (0 to 64) and returns the corresponding value i.
func ParseInt(s string, base int, bitSize int) (i int64, err error)

  • 參數(shù)1 數(shù)字的字符串形式

  • 參數(shù)2 數(shù)字字符串的進制 比如二進制 八進制 十進制 十六進制

  • 參數(shù)3 返回結(jié)果的bit大小 也就是int8 int16 int32 int64

使用示例:

i, err := strconv.ParseInt("123", 10, 32)

“go語言如何將整型轉(zhuǎn)為字符串”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI