Compare()函數是Golang編程語言中的內置函數,用於比較兩個字符串。它用於按字典順序比較兩個字符串(按字母順序排列單詞的順序,類似於我們在字典中搜索單詞的方式),或查找字符串是否相等。它返回一個整數值,如下所示:
用法:
func Compare(s1, s2 string) int
- 如果字符串相等(s1 == s2),則返回0
- 如果字符串1大於字符串2(s1> s2),則返回1。
- 如果字符串1小於字符串2,則返回-1(s1 <s2)
範例1:
// Golang program to illustrate the use of
// the strings.Compare() Function
package main
import (
"fmt"
"strings"
)
func main() {
var s1 = "Geeks"
var s2 = "GeeksforGeeks"
var s3 = "Geeks"
// using the function
fmt.Println(strings.Compare(s1, s2))
fmt.Println(strings.Compare(s2, s3))
fmt.Println(strings.Compare(s3, s1))
}
輸出:
-1 1 0
說明:第一個輸出為-1,因為第一個字符串是“Geeks”,在字典上小於第二個字符串“GeeksforGeeks”。第二輸出為1,因為第一個字符串是“GeeksforGeeks”,在字典上比第二個字符串“Geeks”大。第三輸出為0,因為第一個字符串是“Geeks”,它等於第二個字符串“Geeks”。
範例2:
// Golang program to illustrate the use of
// the strings.Compare() Function
package main
import (
"fmt"
"strings"
)
func main() {
var s1 = "apple"
var s2 = "Apple"
var s3 = "Apricot"
// using the function
fmt.Println(strings.Compare(s1, s2))
fmt.Println(strings.Compare(s2, s3))
fmt.Println(strings.Compare(s3, s1))
}
輸出:
1 -1 -1
說明:第一個輸出為1,因為第一個字符串是“apple”,在字典上大於第二個字符串“Apple”,這是因為使用Unicode字符集從左到右依次比較字符,並且‘a’的ASCII值為97,而'A'的ASCII值是65.因此,蘋果大於蘋果。
第二輸出為-1,因為第一個字符串是“Apple”,在字典上小於第二個字符串“Apricot”。第三輸出為-1,因為第一個字符串是“Apricot”,在字典上小於第二個字符串“apple”,因為“ A”小於第二個字符串‘a’。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自prakhar7大神的英文原創作品 strings.Compare() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。