🐾 在Go中比较字符串的方法实例

107 阅读1分钟

要在Go中比较两个字符串,你可以使用比较运算符 ==,!=,>=,<=,<,> 。或者,你可以使用 strings.Compare()函数,该函数来自 strings包中的函数。

当比较字符串时,我们指的是lexicographic(按字母顺序)顺序

比较运算符

Go中的字符串支持比较运算符==,!=,>=,<=,<,> ,以lexicographic(字母表)的顺序比较字符串。比较的结果是一个bool 值 (truefalse) ,表示是否满足条件。

例子:

package main
import "fmt"
func main() {
str1 := "gosamples"
str2 := "dev"
str3 := "gosamples"
fmt.Printf("%s == %s: %t\n", str1, str2, str1 == str2)
fmt.Printf("%s == %s: %t\n", str1, str3, str1 == str3)
fmt.Printf("%s != %s: %t\n", str1, str2, str1 != str2)
fmt.Printf("%s != %s: %t\n\n", str1, str3, str1 != str3)
fmt.Printf("%s >= %s: %t\n", str1, str2, str1 >= str2)
fmt.Printf("%s >= %s: %t\n", str1, str3, str1 >= str3)
fmt.Printf("%s > %s: %t\n", str1, str2, str1 > str2)
fmt.Printf("%s > %s: %t\n\n", str1, str3, str1 > str3)
fmt.Printf("%s <= %s: %t\n", str1, str2, str1 <= str2)
fmt.Printf("%s <= %s: %t\n", str1, str3, str1 <= str3)
fmt.Printf("%s < %s: %t\n", str1, str2, str1 < str2)
fmt.Printf("%s < %s: %t\n", str1, str3, str1 < str3)
}

输出:

gosamples == dev: false
gosamples == gosamples: true
gosamples != dev: true
gosamples != gosamples: false
gosamples >= dev: true
gosamples >= gosamples: true
gosamples > dev: true
gosamples > gosamples: false
gosamples <= dev: false
gosamples <= gosamples: true
gosamples < dev: false
gosamples < gosamples: false

strings.Compare()函数

strings.Compare()函数将两个字符串按词典顺序进行比较,结果是返回一个int

func Compare(a, b string) int

结果是:

  • 0 如果a == b
  • 1 如果a > b
  • -1 如果a < b

例子:

package main
import (
"fmt"
"strings"
)
func main() {
str1 := "gosamples"
str2 := "dev"
str3 := "gosamples"
fmt.Printf("strings.Compare(%s, %s): %d\n", str1, str2, strings.Compare(str1, str2))
fmt.Printf("strings.Compare(%s, %s): %d\n", str1, str3, strings.Compare(str1, str3))
fmt.Printf("strings.Compare(%s, %s): %d\n", str2, str1, strings.Compare(str2, str1))
}

输出:

strings.Compare(gosamples, dev): 1
strings.Compare(gosamples, gosamples): 0
strings.Compare(dev, gosamples): -1