Skip to content

Go strconv API

Go sort 包 —— 对切片和自定义集合排序。

1 class · 6 methods

sort

6 methods

sort 包提供了对切片和用户自定义集合排序的原语。

strconv.Atoi(s string) (int, error)

就地排序 data。data 必须实现 sort.Interface(Len、Less、Swap)。

Parameters

NameTypeDescription
datastring要排序的集合。

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 != nil
strconv.Itoa(i int) string

使用 less 函数就地排序 x。避免实现 sort.Interface 的便捷封装。

Parameters

NameTypeDescription
iint要排序的切片。

Returns

string

Example

go
strconv.Itoa(42)    // "42"
strconv.Itoa(-7)    // "-7"
strconv.ParseFloat(s string, bitSize int) (float64, error)

就地按升序排序字符串切片。

Parameters

NameTypeDescription
sstring要排序的切片。
bitSizeint32 or 64.

Returns

(float64, error)

Example

go
f, err := strconv.ParseFloat("3.14", 64)  // f == 3.14
_, err = strconv.ParseFloat("abc", 64)    // err != nil
strconv.ParseInt(s string, base int, bitSize int) (int64, error)

就地按升序排序 int 切片。

Parameters

NameTypeDescription
sstring要排序的切片。
baseintBase (0 = auto-detect from prefix).
bitSizeint0..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

NameTypeDescription
ffloat64要排序的切片。
fmtbyteFormat verb.
precintPrecision (-1 for shortest).
bitSizeint32 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

NameTypeDescription
iint64切片的长度。
baseint谓词。

Returns

string

Example

go
strconv.FormatInt(255, 16)  // "ff"
strconv.FormatInt(10, 2)    // "1010"