note4cs/技术/Go/常用包/strconv.md
2025-03-19 14:36:09 +08:00

130 lines
3.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

在 Go 语言中,`strconv` 包提供了许多用于基本数据类型和字符串之间相互转换的函数。以下是一些常用的函数及其功能:
### **1. 字符串与整数之间的转换**
- **`Atoi(s string) (int, error)`**
将字符串转换为整数(十进制)。如果转换失败,会返回错误。
示例:
```go
num, err := strconv.Atoi("123")
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Println("转换结果:", num) // 输出: 转换结果: 123
}
```
- **`Itoa(i int) string`**
将整数转换为字符串。
示例:
```go
str := strconv.Itoa(123)
fmt.Println("转换结果:", str) // 输出: 转换结果: "123"
```
- **`ParseInt(s string, base int, bitSize int) (i int64, err error)`**
将字符串按指定进制和位数转换为整数。
示例:
```go
num, err := strconv.ParseInt("FF", 16, 64)
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Println("转换结果:", num) // 输出: 转换结果: 255
}
```
- **`FormatInt(i int64, base int) string`**
将整数按指定进制格式化为字符串。
示例:
```go
str := strconv.FormatInt(255, 16)
fmt.Println("转换结果:", str) // 输出: 转换结果: "ff"
```
---
### 2. **字符串与浮点数之间的转换**
- **`ParseFloat(s string, bitSize int) (float64, error)`**
将字符串转换为浮点数。
示例:
```go
num, err := strconv.ParseFloat("3.14", 64)
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Println("转换结果:", num) // 输出: 转换结果: 3.14
}
```
- **`FormatFloat(f float64, fmt byte, prec, bitSize int) string`**
将浮点数格式化为字符串。
示例:
```go
str := strconv.FormatFloat(3.14159, 'f', 2, 64)
fmt.Println("转换结果:", str) // 输出: 转换结果: "3.14"
```
---
### 3. **字符串与布尔值之间的转换**
- **`ParseBool(str string) (bool, error)`**
将字符串转换为布尔值。支持的真值包括 `"true"`、`"True"`、`"TRUE"` 等,假值包括 `"false"`、`"False"`、`"FALSE"` 等。
示例:
```go
b, err := strconv.ParseBool("True")
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Println("转换结果:", b) // 输出: 转换结果: true
}
```
- **`FormatBool(b bool) string`**
将布尔值转换为字符串(`"true"` 或 `"false"`)。
示例:
```go
str := strconv.FormatBool(true)
fmt.Println("转换结果:", str) // 输出: 转换结果: "true"
```
---
### 4. **其他常用函数**
- **`Quote(s string) string`**
返回一个带有双引号的字符串字面量表示形式。
示例:
```go
str := strconv.Quote("Hello, World!")
fmt.Println("转换结果:", str) // 输出: 转换结果: "\"Hello, World!\""
```
- **`Unquote(s string) (string, error)`**
移除字符串中的双引号,并还原转义字符。
示例:
```go
str, err := strconv.Unquote("\"Hello, World!\"")
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Println("转换结果:", str) // 输出: 转换结果: Hello, World!
}
```
- **`Append` 系列函数**
这些函数将基本数据类型直接追加到字节切片中,常用于高效的字符串拼接操作。例如:`AppendInt`、`AppendBool`、`AppendFloat` 等。
示例:
```go
b := []byte("数字是: ")
b = strconv.AppendInt(b, 123, 10)
fmt.Println(string(b)) // 输出: 数字是: 123
```
> 在 `strconv.AppendInt(b, 123, 10)` 中第三个参数表示数字的进制base。具体来说
> **`10`** 表示将整数 `123` 按照十进制格式追加到字节切片 `b` 中。如果改为其他值,例如 `16`则表示将整数以十六进制格式追加;如果是 `2`,则表示以二进制格式追加。