如何在 Golang 中判斷一個字串是否包含特定的字首字串?


在 Golang 語言中,string 類中的 HasPrefix() 函式用於判斷給定的字串是否以特定字首字串開頭。如果給定的字串以指定的字首字串開頭,則返回 True;否則,返回 False

語法

func HasPrefix(s, prefix string) bool

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

示例

在這個例子中,我們將使用 HasPrefix() 以及 if 條件來檢查所定義的兩個變數是否以相同的字首字串開頭。

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   // Initializing the Strings
   p := "HasPrefix Function is quite useful."
   q := "Has"

   // Display the Strings
   fmt.Println("String 1:", p)
   fmt.Println("String 2:", q)

   // Using the HasPrefix Function
   if strings.HasPrefix(p, q) == true {
      fmt.Println("Both the strings have the same prefix.")
   } else {
      fmt.Println("The strings don't start with the same prefix.")
   }
}

輸出

它將生成以下輸出 −

String 1: HasPrefix Function is quite useful.
String 2: Has
Both the strings have the same prefix.

示例

讓我們再舉一個例子

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

   // Initializing the Strings
   x := "Go HasPrefix String Function"

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

   // Using the HasPrefix Function
   result1 := strings.HasPrefix(x, "Go")
   result2 := strings.HasPrefix(x, "Golang")

   // Display the HasPrefix Output
   fmt.Println("Given String has the prefix 'Go'? :", result1)
   fmt.Println("Given String has the prefix 'Golang'? :", result2)
}

輸出

它將生成以下輸出 −

Given String: Go HasPrefix String Function
Given String has the prefix 'Go'? : true
Given String has the prefix 'Golang'? : false

更新時間:2022-03-10

4K+ 瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告