如何在 Go 語言中比較兩個字串?


Go 語言內建了一個名為 Compare() 的字串函式,我們可以使用該函式比較兩個字串。此函式使用字典序比較字串。

語法

func Compare(a, b string) int

返回型別

  • 如果字串 (a == b),則返回 0。
  • 如果字串 (a > b),則返回 1
  • 如果字串 (a < b),則返回 -1

示例

我們考慮一下以下示例 −

package main
// importing fmt and strings
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the variables
   var a1 = "a"
   var a2 = "b"
   var a3 = "welcome"
   var a4 = "Golang"
   
   // using the Compare function
   // a1 < a2; it will return -1
   fmt.Println(strings.Compare(a1, a2))
   
   // a2 > a1; it will return 1
   fmt.Println(strings.Compare(a2, a1))
   
   // a3 > a4; it will return 1
   fmt.Println(strings.Compare(a3, a4))
   
   // a4 < a3; it will return -1
   fmt.Println(strings.Compare(a4, a3))
   
   // a1 == a1; it will return 0
   fmt.Println(strings.Compare(a1, a1))
}

輸出

我們考慮一下以下示例 −

-1
1
1
-1
0

示例

在此示例中,我們將使用 if 條件以及 Compare() 函式檢查兩個字串是否相同。

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the variables
   A := "Golang on Tutorialspoint"
   B := "Golang on Tutorialspoint"
   
   // using the Compare function
   if strings.Compare(A, B) == 0 {
      fmt.Println("Both the strings match.")
   } else {
      fmt.Println("The strings do not match.")
   }
}

輸出

由於兩個字串相等,因此程式將生成以下輸出 −

Both the strings match.

更新於: 10-Mar-2022

4 千次瀏覽

提升您的職業

完成課程以獲得認證

開始
廣告