Technology Sharing

Simple use of hassuffix in go language

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In Go language, `strings` package provides `HasSuffix` function, which is used to check whether a string ends with a specified suffix. This function returns a Boolean value, if the string ends with the specified suffix, it returns `true`, otherwise it returns `false`.

 

The following is a basic usage example of the `HasSuffix` function:

 

```go

package main

 

import (

 "fmt"

 "strings"

)

 

func main() {

// Example string

 str := "hello.txt"

 

// Check if the string ends with ".txt"

 if strings.HasSuffix(str, ".txt") {

fmt.Println("The string ends with '.txt'")

 } else {

fmt.Println("The string does not end with '.txt'")

 }

 

// Check if the string ends with ".go"

 if strings.HasSuffix(str, ".go") {

fmt.Println("The string ends with '.go'")

 } else {

fmt.Println("The string does not end with '.go'")

 }

}

```

 

When you run the above code, the output will be:

 

```

The string ends with '.txt'

The string does not end with '.go'

```

 

This example demonstrates how to use the `strings.HasSuffix` function to check if a string ends with a specific suffix. Note that the suffix check is case sensitive, so ".Txt" and ".txt" are considered different suffixes. If you need a case-insensitive check, you may want to convert the string or the suffix to lowercase or uppercase before calling `HasSuffix`.

 

For example, to perform a case-insensitive suffix check:

 

```go

suffix := ".txt"

if strings.HasSuffix(strings.ToLower(str), strings.ToLower(suffix)) {

fmt.Println("String (case insensitive) ends with '.txt'")

}

```