String
6 methodsString 类表示字符串。所有字符串字面量都是 String 的实例。
sort.Sort(data sort.Interface)返回此字符串的长度。
Parameters
| Name | Type | Description |
|---|---|---|
| data | sort.Interface | Collection to sort. |
Returns
void
Example
go
type ByLen []string
func (a ByLen) Len() int { return len(a) }
func (a ByLen) Less(i,j int) bool { return len(a[i]) < len(a[j]) }
func (a ByLen) Swap(i,j int) { a[i], a[j] = a[j], a[i] }
sort.Sort(ByLen{"bb", "a", "ccc"})
// ["a", "bb", "ccc"]sort.Slice(x any, less func(i, j int) bool)返回指定索引处的 char 值。抛出 StringIndexOutOfBoundsException。
Parameters
| Name | Type | Description |
|---|---|---|
| index | any | 从 0 开始的索引。 |
| less | func(i, j int) bool | Less comparator. |
Returns
void
Example
go
s := []string{"bb", "a", "ccc"}
sort.Slice(s, func(i, j int) bool {
return len(s[i]) < len(s[j])
})
// s == ["a", "bb", "ccc"]sort.Strings(a []string)返回一个新字符串,作为此字符串从 beginIndex 到 endIndex(不包含)的子字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| beginIndex | []string | 起始(包含)。 |
Returns
void
Example
go
s := []string{"c", "a", "b"}
sort.Strings(s)
// s == ["a", "b", "c"]sort.Ints(a []int)返回 str 首次出现的索引,未找到则返回 -1。
Parameters
| Name | Type | Description |
|---|---|---|
| str | []int | 要查找的子字符串。 |
Returns
void
Example
go
n := []int{3, 1, 2}
sort.Ints(n)
// n == [1, 2, 3]sort.Float64s(a []float64)按给定正则表达式的匹配分割此字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| regex | []float64 | 作为分隔符的正则表达式。 |
Returns
void
Example
go
f := []float64{3.1, 1.2, 2.5}
sort.Float64s(f)
// f == [1.2, 2.5, 3.1]sort.Search(n int, f func(int) bool) int返回移除首尾空白字符(码点 <= U+0020)后的新字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| n | int | Length of the slice. |
| f | func(int) bool | Predicate. |
Returns
int
Example
go
a := []int{1, 3, 5, 7, 9}
i := sort.Search(len(a), func(i int) bool { return a[i] >= 5 })
// i == 2, a[i] == 5