在 Golang 中,可以使用 strings.HasPrefix() 函数来判断一个字符串是否以指定的前缀开头。该函数的用法如下:

func HasPrefix(s, prefix string) bool

其中,参数 s 是要判断的字符串,参数 prefix 是要匹配的前缀。如果字符串 sprefix 开头,则函数返回 true,否则返回 false

以下是一个示例代码:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "hello world"

	// 判断字符串是否以 'hello' 开头
	if strings.HasPrefix(str, "hello") {
		fmt.Println("字符串以 hello 开头")
	} else {
		fmt.Println("字符串不以 hello 开头")
	}

	// 判断字符串是否以 'world' 开头
	if strings.HasPrefix(str, "world") {
		fmt.Println("字符串以 world 开头")
	} else {
		fmt.Println("字符串不以 world 开头")
	}
}

输出结果为:

字符串以 hello 开头
字符串不以 world 开头

通过以上示例代码,可以看到如何在 Golang 中进行字符串的前缀匹配。

Golang 字符串前缀匹配 - 使用 strings.HasPrefix() 函数

原文地址: https://www.cveoy.top/t/topic/o9of 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录