sort
6 methodssort 包提供了对切片和用户自定义集合排序的原语。
strconv.Atoi(s string) (int, error)就地排序 data。data 必须实现 sort.Interface(Len、Less、Swap)。
Parameters
| Name | Type | Description |
|---|---|---|
| data | string | 要排序的集合。 |
Returns
(int, error)
Example
go
n, err := strconv.Atoi("42") // n == 42, err == nil
_, err = strconv.Atoi("4.2") // err != nil
_, err = strconv.Atoi("abc") // err != nilstrconv.Itoa(i int) string使用 less 函数就地排序 x。避免实现 sort.Interface 的便捷封装。
Parameters
| Name | Type | Description |
|---|---|---|
| i | int | 要排序的切片。 |
Returns
string
Example
go
strconv.Itoa(42) // "42"
strconv.Itoa(-7) // "-7"strconv.ParseFloat(s string, bitSize int) (float64, error)就地按升序排序字符串切片。
Parameters
| Name | Type | Description |
|---|---|---|
| s | string | 要排序的切片。 |
| bitSize | int | 32 or 64. |
Returns
(float64, error)
Example
go
f, err := strconv.ParseFloat("3.14", 64) // f == 3.14
_, err = strconv.ParseFloat("abc", 64) // err != nilstrconv.ParseInt(s string, base int, bitSize int) (int64, error)就地按升序排序 int 切片。
Parameters
| Name | Type | Description |
|---|---|---|
| s | string | 要排序的切片。 |
| base | int | Base (0 = auto-detect from prefix). |
| bitSize | int | 0..64. |
Returns
(int64, error)
Example
go
n, _ := strconv.ParseInt("ff", 16, 64) // n == 255
n, _ = strconv.ParseInt("0b11", 0, 64) // n == 3 (auto base)strconv.FormatFloat(f float64, fmt byte, prec, bitSize int) string就地按升序排序 float64 切片。
Parameters
| Name | Type | Description |
|---|---|---|
| f | float64 | 要排序的切片。 |
| fmt | byte | Format verb. |
| prec | int | Precision (-1 for shortest). |
| bitSize | int | 32 or 64. |
Returns
string
Example
go
strconv.FormatFloat(3.14, 'f', 2, 64) // "3.14"
strconv.FormatFloat(3.14, 'g', -1, 64) // "3.14"strconv.FormatInt(i int64, base int) string二分查找。使用 f 在 [0,n) 中找到使 f(i) 为 true 的最小索引 i。
Parameters
| Name | Type | Description |
|---|---|---|
| i | int64 | 切片的长度。 |
| base | int | 谓词。 |
Returns
string
Example
go
strconv.FormatInt(255, 16) // "ff"
strconv.FormatInt(10, 2) // "1010"