GolangTip:bytes.Compare按字典顺序比较

2018-09-28  本文已影响0人  幸运排骨虾

维基百科关于字典顺序的例子:

Given two different sequences of the same length, a1a2...ak and b1b2...bk, the first one is smaller than the second one for the lexicographical order, if ai<bi (for the order of A), for the first i where ai and bi differ.

简单说就是给定两个串,分别从每个串的开始依次比较串的元素的大小,当第一个不同的元素出现时(ai != bi)比较就结束了,且ai与bi的比较结果作为串比较的结果。

此外,短串跟长串相比时,短串不足的位置会作为空元素处理,且空元素比其它非空元素小。

package main

import (
    "bytes"
    "fmt"
)

func main() {
    sa := []byte{2, 3}
    sb := []byte{12, 3}
    sc := []byte{3}
    sd := []byte{2,1,5}
    fmt.Println("sa.comp(sb)", bytes.Compare(sa, sb))
    fmt.Println("sa.comp(sc)", bytes.Compare(sa, sc))
    fmt.Println("sa.comp(sd)", bytes.Compare(sa, sd))
}

点击运行查看结果

上一篇 下一篇

猜你喜欢

热点阅读