Go語言程式比較兩個字串


在Go程式語言中,字串是一種可用於各種應用程式的資料型別。它是由字元組成的集合,並且是不可變的。在Go程式語言中,字串一旦建立就不能修改。在本文中,我們將學習比較兩個給定字串的不同技術。

語法

bytes.Equal(s1,s2)

使用Equal()方法比較兩個位元組切片([]byte)是否相等。如果兩個位元組切片相等,則會產生一個反映該事實的布林結果(true或false)。

strings.Compare(s1,s2)

Compare()函式用於按字典順序比較兩個字串。它返回一個整數,表示比較結果:

如果兩個字串相同,則值為0。

如果第一個字串按字典順序小於第二個字串,則值為小於0。

如果第一個字串按字典順序大於第二個字串,則值為大於0。

演算法

  • 步驟1 - 建立一個名為main的包並宣告fmt(格式化包)

  • 步驟2 - 在main函式中,建立兩個變數

  • 步驟3 - 將您想要比較的兩個字串賦值給它們。

  • 步驟4 - 使用內部函式或使用者定義函式比較兩個字串

  • 步驟5 - 列印輸出。

示例1

在這個例子中,我們將看到如何在Golang中使用if-else語句比較兩個字串。

package main
import (
   "fmt"
)
func main() {
   mystr1 := "create" //create str1
   fmt.Println("The string1 created here is:", mystr1)
   mystr2 := "craete" //create str2
   fmt.Println("The string2 created here is:", mystr2)
   fmt.Println("Are the strings equal?")
   if mystr1 == mystr2 {
      fmt.Println("The strings are equal.") //print strings are equal
   } else {
      fmt.Println("The strings are not equal.") //print strings are not equal
   }
}

輸出

The string1 created here is: create
The string2 created here is: craete
Are the strings equal?
The strings are not equal.

示例2

在這個例子中,我們將使用bytes.Equal()函式來比較兩個字串

package main
import (
   "bytes"
   "fmt"
)
func main() {
   mystr1 := "create" //create string1
   fmt.Println("The string1 created here is:", mystr1)
   mystr2 := "craete" //create string2
   fmt.Println("The string2 created here is:", mystr2)
   fmt.Println("Are the strings equal?")
   if bytes.Equal([]byte(mystr1), []byte(mystr2)) { //use bytes.Equal() function to compare slices
      fmt.Println("The strings are equal.") //print strings are not equal
   } else {
      fmt.Println("The strings are not equal.") //print strings are equal
   }
}

輸出

The string1 created here is: create
The string2 created here is: craete
Are the strings equal?
The strings are not equal.

示例3

在這個例子中,我們將使用strings.compare()函式來比較兩個切片。

package main
import (
   "fmt"
   "strings"
)
func main() {
   mystr1 := "create" //create string1
   fmt.Println("The string1 created here is:", mystr1)
   mystr2 := "craete" //create string2
   fmt.Println("The string2 created here is:", mystr2)
   fmt.Println("Are the strings equal?")
   if strings.Compare(mystr1, mystr2) == 0 { //use strings.compare function
      fmt.Println("The strings are equal.") //print slices are equal
   } else {
      fmt.Println("The strings are not equal") //print slices are not equal
   }
}

輸出

The string1 created here is: create
The string2 created here is: craete
Are the strings equal?
The strings are not equal

結論

我們使用三種方法執行了比較兩個字串的程式。在第一種方法中,我們使用了簡單的比較運算子;在第二個例子中,我們使用了bytes.Equal()函式;在第三個例子中,我們使用了strings.Compare()函式。

更新於:2023年2月13日

623 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告