Skip to content

Java sort API

Java String 方法 —— 不可变字符序列。

1 class · 6 methods

String

6 methods

String 类表示字符串。所有字符串字面量都是 String 的实例。

sort.Sort(data sort.Interface)

返回此字符串的长度。

Parameters

NameTypeDescription
datasort.InterfaceCollection 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

NameTypeDescription
indexany从 0 开始的索引。
lessfunc(i, j int) boolLess 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

NameTypeDescription
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

NameTypeDescription
str[]int要查找的子字符串。

Returns

void

Example

go
n := []int{3, 1, 2}
sort.Ints(n)
// n == [1, 2, 3]
sort.Float64s(a []float64)

按给定正则表达式的匹配分割此字符串。

Parameters

NameTypeDescription
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

NameTypeDescription
nintLength of the slice.
ffunc(int) boolPredicate.

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