如何在 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+ 浏览量

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.