在Go语言中,检查一个给定的字符串是否以另一个子串开始真的很简单。在许多编程语言中,都有一个startsWith() 函数来完成这个任务。在Go中,我们有 HasPrefix()来自于 strings包中。当一个子串是一个字符串的前缀时,它返回真,否则返回假。
package main
import (
"fmt"
"strings"
)
const name = "GOSAMPLES"
func main() {
fmt.Printf("GO is at the beginning of GOSAMPLES: %t\n", strings.HasPrefix(name, "GO"))
fmt.Printf("SAMPLES is at the beginning of GOSAMPLES: %t\n", strings.HasPrefix(name, "SAMPLES"))
}
输出
GO is at the beginning of GOSAMPLES: true
SAMPLES is at the beginning of GOSAMPLES: false