如何从字符串中删除最后 4 个字符?

Kai*_*ive 4 string go

我想从字符串中删除最后 4 个字符,因此“test.txt”变为“test”。

package main

import (
    "fmt"
    "strings"
)

func main() {
    file := "test.txt"
    fmt.Print(strings.TrimSuffix(file, "."))
}
Run Code Online (Sandbox Code Playgroud)

col*_*tor 5

这将安全地删除任何点扩展名 - 如果未找到扩展名,则可以容忍:

func removeExtension(fpath string) string {
        ext := filepath.Ext(fpath)
        return strings.TrimSuffix(fpath, ext)
}
Run Code Online (Sandbox Code Playgroud)

游乐场的例子

表测试:

/www/main.js                             -> '/www/main'
/tmp/test.txt                            -> '/tmp/test'
/tmp/test2.text                          -> '/tmp/test2'
/tmp/test3.verylongext                   -> '/tmp/test3'
/user/bob.smith/has.many.dots.exe        -> '/user/bob.smith/has.many.dots'
/tmp/zeroext.                            -> '/tmp/zeroext'
/tmp/noext                               -> '/tmp/noext'
                                         -> ''
Run Code Online (Sandbox Code Playgroud)