例如,我有一个字符串,由“sample.zip”组成。如何使用字符串包或其他方法删除“.zip”扩展名?
6 回答
尝试:
basename := "hello.blah"
name := strings.TrimSuffix(basename, filepath.Ext(basename))
TrimSuffix 基本上告诉它去除尾随字符串,即带有点的扩展名。
Edit: Go has moved on. Please see Keith's answer.
Use path/filepath.Ext to get the extension. You can then use the length of the extension to retrieve the substring minus the extension.
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = filename[0:len(filename)-len(extension)]
Alternatively you could use strings.LastIndex to find the last period (.) but this may be a little more fragile in that there will be edge cases (e.g. no extension) that filepath.Ext
handles that you may need to code for explicitly, or if Go were to be run on a theoretical O/S that uses a extension delimiter other than the period.
这种方式也有效:
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = TrimRight(filename, extension)
但也许 Paul Ruane 的方法更有效?
我正在使用 go1.14.1,filepath.Ext
对我没用,对我没path.Ext
问题
var fileName = "hello.go"
fileExtension := path.Ext(fileName)
n := strings.LastIndex(fileName, fileExtension)
fmt.Println(fileName[:n])
游乐场: https: //play.golang.org/p/md3wAq_obNc
这是不需要path
or的示例path/filepath
:
func BaseName(s string) string {
n := strings.LastIndexByte(s, '.')
if n == -1 { return s }
return s[:n]
}
它似乎也比它更快TrimSuffix
:
PS C:\> go test -bench .
goos: windows
goarch: amd64
BenchmarkTrimFile-12 166413693 7.25 ns/op
BenchmarkTrimPath-12 182020058 6.56 ns/op
BenchmarkLast-12 367962712 3.28 ns/op
这只是性能更高的一行。这里是:
filename := strings.Split(file.Filename, ".")[0]