Golang 检查字符串是否以指定的后缀结束

Golang 检查字符串是否以指定的后缀结束

在Go语言中,字符串与其他语言如Java , C++ , Python等不同。它是一个可变宽度的字符序列,每个字符都由一个或多个使用UTF-8编码的字节表示。

在Go语言的字符串中,你可以借助 HasSuffix() 函数来检查字符串是否以指定的后缀结束。如果给定的字符串以指定的后缀结束,该函数返回真,如果给定的字符串不以指定的后缀结束,则返回假。它被定义在strings包下,因此,你必须在你的程序中导入strings包以访问HasSuffix函数。

语法

func HasSuffix(str, suf string) bool

这里,str是原始字符串,suf是代表后缀的字符串。这个函数的返回类型是bool类型。

例子

// Go program to illustrate how to check the
// given string start 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 HasSuffix() function
    res1 := strings.HasSuffix(s1, "GeeksforGeeks!")
    res2 := strings.HasSuffix(s1, "!")
    res3 := strings.HasSuffix(s1, "Apple")
    res4 := strings.HasSuffix(s2, "language!")
    res5 := strings.HasSuffix(s2, "dog")
    res6 := strings.HasSuffix("GeeksforGeeks, Geeks", "Geeks")
    res7 := strings.HasSuffix("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)
    fmt.Println("Result 7: ", res7)
}

输出

Result 1:  true
Result 2:  true
Result 3:  false
Result 4:  true
Result 5:  false
Result 6:  true
Result 7:  false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程