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

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

Golang中 字符串 类的 HasSuffix() 函数是用来检查一个给定的字符串是否以指定的Suffix字符串结尾。如果给定的字符串以指定的Suffix字符串结尾,则返回True;否则返回False。

HasSuffix()HasPrefix() 分别检查一个字符串是否以一组特定的字符结束或开始。

语法

func HasSuffix(s, prefix string) bool
Go

其中x是给定的字符串。它返回一个布尔值。

例子1

在这个例子中,我们将使用 HasSuffix() 和一个if条件来检查两个定义的字符串变量是否以相同的字符集结束。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   m := "HasSuffix String"
   n := "String"

   // Display the Strings
   fmt.Println("String 1: ", m)
   fmt.Println("String 2: ", n)

   // Using the HasSuffix Function
   if strings.HasSuffix(m, n) == true {
      fmt.Println("Both the strings have the same suffix.")
   } else {
      fmt.Println("Strings do not end with the same suffix.")
   }
}
Go

输出

它将产生以下输出 –

String 1: HasSuffix String
String 2: String
Both the strings have the same suffix.
Go

例子2

现在,让我们来看看 HasSuffix( )的另一个例子 。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   y := "HasSuffix String Function"

   // Display the Strings
   fmt.Println("Given String:", y)

   // Using the HasSuffix Function
   test1 := strings.HasSuffix(y, "Function")
   test2 := strings.HasSuffix(y, "String")

   // Display the HasSuffix Output
   fmt.Println("The Given String has the Suffix 'Function'? :", test1)
   fmt.Println("The Given String has the Suffix 'String'? :", test2)
}
Go

输出

它将产生以下输出 –

Given String: HasSuffix String Function
The Given String has the Suffix 'Function'? : true
The Given String has the Suffix 'String'? : false
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册