如何在Go语言中检查字符串是否以指定的字尾字符串结尾?


Go语言中**string**类的**HasSuffix()**函数用于检查给定字符串是否以指定的字尾字符串结尾。如果给定字符串以指定的字尾字符串结尾,则返回True;否则返回False。

**HasSuffix()**和**HasPrefix()**分别检查字符串是否以特定字符集结尾或开头。

语法

func HasSuffix(s, prefix string) bool

其中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.")
   }
}

输出

它将生成以下输出:

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

示例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)
}

输出

它将生成以下输出:

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

更新于:2022年3月10日

2K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.