Go language obtains the name, prefix and suffix of the file

Time:2021-8-22

Example code:


package main
import (
    "fmt"
    "path"
)
func main() {
    filename := "device/sdk/CMakeLists.txt"
    filenameall := path.Base(filename)    
    filesuffix := path.Ext(filename)
    fileprefix := filenameall[0:len(filenameall) - len(filesuffix)]
    //fileprefix, err := strings.TrimSuffix(filenameall, filesuffix)
    fmt.Println("file name:", filenameall)
    fmt.Println("file prefix:", fileprefix)
    fmt.Println("file suffix:", filesuffix)
}

Execution results:

file name: CMakeLists.txt

file prefix: CMakeLists

file suffix: .txt

path.Base(filename) Gets the file name that does not contain a directory

path.Ext(filename) Get file suffix

The file prefix can be obtained by slicing:


fileprefix := filenameall[0:len(filenameall) - len(filesuffix)]

You can also use strings. Trimsuffix() to get:


import "strings"
fileprefix, err := strings.TrimSuffix(filenameall, filesuffix)

Supplement: golang judges prefix, suffix and inclusion relationship

Hasprefix determines whether the string s starts with prefix:


strings.HasPrefix(s, prefix string) bool

Hassuffix determines whether the string s ends with suffix:


strings.HasSuffix(s, suffix string) bool

String containment relationship

Contains determines whether the string s contains substr:


strings.Contains(s, substr string) bool

Test source code:


package main
import (
        "fmt"
        "strings"
)
func main() {
        var str1 string = "This is an example of a string"
        var str2 string = "this is an "
        var str3 string = " of a string"
        fmt.Println(strings.HasPrefix(str1, str2))
        fmt.Println(strings.HasSuffix(str1, str3))
}

Operation results:

[[email protected] golang]# go run zzz.go

false

true

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.

Recommended Today

Eslint first experience

start //Install eslint //Local installation npm i –save-dev eslint //Or global installation npm i -g eslint use eslint –init After that, several options will appear. You can know what they mean by looking at the options. Here, focus on the first and second options Popular configuration The first option is to select some popular specifications, […]