如何在Go語言中檢查字串是否以指定的字尾字串結尾?


Go語言中**string**類的**HasSuffix()**函式用於檢查給定字串是否以指定的字尾字串結尾。如果給定字串以指定的字尾字串結尾,則返回True;否則返回False。

**HasSuffix()**和**HasPrefix()**分別檢查字串是否以特定字元集結尾或開頭。

語法

func HasSuffix(s, prefix string) bool

其中x是給定的字串。它返回一個布林值。

示例1

在這個例子中,我們將使用**HasSuffix()**和if條件來檢查兩個定義的字串變數是否以相同的字元集結尾。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   m := "HasSuffix String"
   n := "String"

   // Display the Strings
   fmt.Println("String 1: ", m)
   fmt.Println("String 2: ", n)

   // Using the HasSuffix Function
   if strings.HasSuffix(m, n) == true {
      fmt.Println("Both the strings have the same suffix.")
   } else {
      fmt.Println("Strings do not end with the same suffix.")
   }
}

輸出

它將生成以下輸出:

String 1: HasSuffix String
String 2: String
Both the strings have the same suffix.

示例2

現在,讓我們來看另一個**HasSuffix()**的例子。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   y := "HasSuffix String Function"

   // Display the Strings
   fmt.Println("Given String:", y)

   // Using the HasSuffix Function
   test1 := strings.HasSuffix(y, "Function")
   test2 := strings.HasSuffix(y, "String")

   // Display the HasSuffix Output
   fmt.Println("The Given String has the Suffix 'Function'? :", test1)
   fmt.Println("The Given String has the Suffix 'String'? :", test2)
}

輸出

它將生成以下輸出:

Given String: HasSuffix String Function
The Given String has the Suffix 'Function'? : true
The Given String has the Suffix 'String'? : false

更新於:2022年3月10日

2K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告