Golang 如何检查一个字符串是否以指定的前缀字符串开始
Golang中 字符串 类的 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