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)
}
🛒 站长推荐(京东联盟)
- 《Go 程序设计语言》(Go 语言圣经,机械工业出版社) —— Go 官方团队出品,公认入门第一书
- 《Go 语言实战》(异步图书,人民邮电出版社) —— 实战导向,面试前巩固工程手感
- 《Go 语言编程之旅:一起用 Go 做项目》(博文视点,电子工业出版社) —— 项目驱动入门,从零写出完整应用
- Keychron K1Max 矮轴机械键盘(Mac/Win 双系统,QMK/VIA 开源改键) —— 轻薄矮轴 + 开源固件,程序员桌面常客
- 罗技 MX Master 3S 无线鼠标(Flow 跨屏,静音电磁滚轮) —— 人体工学设计,写代码一整天手不酸
以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。