gopl-zh.github.com/ch3/ch3-05-5.md

42 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 3.5.5. 字符串和數字的轉換
除了字符串、字符、字節之間的轉換字符串和數值之間的轉換也比較常見。由strconv包提供這類轉換功能。
將一個整數轉爲字符串一種方法是用fmt.Sprintf返迴一個格式化的字符串另一個方法是用strconv.Itoa(“整數到ASCII”)
```Go
x := 123
y := fmt.Sprintf("%d", x)
fmt.Println(y, strconv.Itoa(x)) // "123 123"
```
FormatInt和FormatUint函數可以用不同的進製來格式化數字
```Go
fmt.Println(strconv.FormatInt(int64(x), 2)) // "1111011"
```
fmt.Printf函數的%b、%d、%u和%x等參數提供功能往往比strconv包的Format函數方便很多特别是在需要包含附加額外信息的時候
```Go
s := fmt.Sprintf("x=%b", x) // "x=1111011"
```
如果要將一個字符串解析爲整數可以使用strconv包的Atoi或ParseInt函數還有用於解析無符號整數的ParseUint函數
```Go
x, err := strconv.Atoi("123") // x is an int
y, err := strconv.ParseInt("123", 10, 64) // base 10, up to 64 bits
```
ParseInt函數的第三個參數是用於指定整型數的大小例如16表示int160則表示int。在任何情況下返迴的結果y總是int64類型你可以通過強製類型轉換將它轉爲更小的整數類型。
有時候也會使用fmt.Scanf來解析輸入的字符串和數字特别是當字符串和數字混合在一行的時候它可以靈活處理不完整或不規則的輸入。