Golang 中的 字符串HasSuffix()类函数用于检查给定的字符串是否以指定的 Suffix 字符串结尾。如果给定的字符串以指定的 Suffix 字符串结尾,则返回 True;否则返回 False。
HasSuffix()并分别检查字符串是否以特定的字符集结束或开始。 HasPrefix()
语法
func HasSuffix(s, prefix string) bool
其中 x 是给定的字符串。它返回一个布尔值。
示例 1
在此示例中,我们将使用if 条件来检查两个已定义的字符串变量是否以相同的字符集结尾。 HasSuffix()
package main import ( "fmt" "strings" ) func main() { //初始化字符串 m := "HasSuffix String" n := "String" //显示字符串 fmt.Println("字符串 1: ", m) fmt.Println("字符串 2: ", n) //使用 HasSuffix 函数 if strings.HasSuffix(m, n) == true { fmt.Println("两个字符串具有相同的后缀。") } else { fmt.Println("字符串不以相同的后缀结尾。") } }输出结果
它将生成以下输出 -
字符串 1: HasSuffix String 字符串 2: String 两个字符串具有相同的后缀。
示例 2
现在,让我们再举一个例子HasSuffix()。
package main import ( "fmt" "strings" ) func main() { //初始化字符串 y := "HasSuffix String Function" //显示字符串 fmt.Println("给定字符串:", y) //使用 HasSuffix 函数 test1 := strings.HasSuffix(y, "Function") test2 := strings.HasSuffix(y, "String") //显示 HasSuffix 输出 fmt.Println("The Given String has the Suffix 'Function'? :", test1) fmt.Println("The Given String has the Suffix 'String'? :", test2) }输出结果
它将生成以下输出 -
给定字符串: HasSuffix String Function The Given String has the Suffix 'Function'? : true The Given String has the Suffix 'String'? : false