Golang 检查字符串是否以指定的前缀开始
在Go语言中,字符串与其他语言如Java , C++ , Python等不同。它是一个可变宽度的字符序列,每一个字符都由一个或多个使用UTF-8编码的字节表示。
在Golang的字符串中,你可以在 HasPrefix() 函数的帮助下检查字符串是否以指定的前缀开始。如果给定的字符串以指定的前缀开始,该函数返回真,如果给定的字符串不以指定的前缀开始,则返回假。它被定义在strings包下,因此,你必须在你的程序中导入strings包以访问HasPrefix函数。
语法
func HasPrefix(str, pre string) bool
这里,str是原始字符串,pre是一个代表前缀的字符串。这个函数的返回类型是bool类型。让我们借助于一个例子来讨论这个概念。
例子
// Go program to illustrate how to check
// the given string starts with the
// specified prefix
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing strings
// Using shorthand declaration
s1 := "I am working as a Technical content writer in GeeksforGeeks!"
s2 := "I am currently writing articles on Go language!"
// Checking the given strings starts with the specified prefix
// Using HasPrefix() function
res1 := strings.HasPrefix(s1, "I")
res2 := strings.HasPrefix(s1, "My")
res3 := strings.HasPrefix(s2, "I")
res4 := strings.HasPrefix(s2, "We")
res5 := strings.HasPrefix("GeeksforGeeks", "Welcome")
res6 := strings.HasPrefix("Welcome to GeeksforGeeks", "Welcome")
// Displaying results
fmt.Println("Result 1: ", res1)
fmt.Println("Result 2: ", res2)
fmt.Println("Result 3: ", res3)
fmt.Println("Result 4: ", res4)
fmt.Println("Result 5: ", res5)
fmt.Println("Result 6: ", res6)
}
输出
Result 1: true
Result 2: false
Result 3: true
Result 4: false
Result 5: false
Result 6: true
极客教程