strconv
Golang 标准库 - strconv
strconv 包实现了基本数据类型的字符串表示之间的转换。
主要功能说明:
-
字符串转整数:
Atoi()字符串转 intParseInt()解析各种进制的整数ParseUint()解析无符号整数
-
字符串转浮点数:
ParseFloat()解析浮点数ParseBool()解析布尔值
-
基本类型转字符串:
Itoa()int 转字符串FormatInt()格式化整数FormatFloat()格式化浮点数FormatBool()格式化布尔值
-
追加到字节切片:
AppendInt()追加整数AppendFloat()追加浮点数AppendBool()追加布尔值AppendQuote()追加带引号的字符串
func main() {
// 1. 字符串转整数
fmt.Println("=== 字符串转整数 ===")
// Atoi - 简单转换
i, err := strconv.Atoi("42")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Atoi: %d (type: %T)\n", i, i)
// ParseInt - 带进制和位数的转换
x, _ := strconv.ParseInt("1010", 2, 64) // 二进制
fmt.Printf("ParseInt(binary): %d\n", x)
y, _ := strconv.ParseInt("FF", 16, 64) // 十六进制
fmt.Printf("ParseInt(hex): %d\n", y)
z, _ := strconv.ParseInt("-42", 10, 32)
fmt.Printf("ParseInt(decimal): %d\n", z)
// ParseUint - 无符号整数
u, _ := strconv.ParseUint("255", 10, 64)
fmt.Printf("ParseUint: %d\n", u)
// 2. 字符串转浮点数和布尔值
fmt.Println("\n=== 字符串转浮点数/布尔值 ===")
f, _ := strconv.ParseFloat("3.14159", 64)
fmt.Printf("ParseFloat: %f\n", f)
b, _ := strconv.ParseBool("true")
fmt.Printf("ParseBool: %t\n", b)
// 3. 基本类型转字符串
fmt.Println("\n=== 基本类型转字符串 ===")
// Itoa - int 转 string
s1 := strconv.Itoa(123)
fmt.Printf("Itoa: %q\n", s1)
// FormatInt - 按进制格式化
s2 := strconv.FormatInt(255, 16)
fmt.Printf("FormatInt(hex): %q\n", s2)
s3 := strconv.FormatInt(255, 2)
fmt.Printf("FormatInt(binary): %q\n", s3)
// FormatFloat
s4 := strconv.FormatFloat(3.14159, 'f', 2, 64)
fmt.Printf("FormatFloat(f): %q\n", s4)
s5 := strconv.FormatFloat(3.14159, 'e', 2, 64)
fmt.Printf("FormatFloat(e): %q\n", s5)
// FormatBool
s6 := strconv.FormatBool(true)
fmt.Printf("FormatBool: %q\n", s6)
// 4. 追加到字节切片
fmt.Println("\n=== 追加到字节切片 ===")
buf := []byte("Numbers: ")
buf = strconv.AppendInt(buf, 42, 10)
buf = append(buf, ", "...)
buf = strconv.AppendFloat(buf, 3.14, 'f', 2, 64)
fmt.Println(string(buf))
// 带引号的字符串
quoted := strconv.Quote("hello\nworld")
fmt.Printf("Quote: %s\n", quoted)
unquoted, _ := strconv.Unquote(`"hello\nworld"`)
fmt.Printf("Unquote: %q\n", unquoted)
}