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、%o和%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来解析输入的字符串和数字特别是当字符串和数字混合在一行的时候它可以灵活处理不完整或不规则的输入。