83

例如,我有一个字符串,由“sample.zip”组成。如何使用字符串包或其他方法删除“.zip”扩展名?

4

6 回答 6

257

尝试:

basename := "hello.blah"
name := strings.TrimSuffix(basename, filepath.Ext(basename))

TrimSuffix 基本上告诉它去除尾随字符串,即带有点的扩展名。

字符串#TrimSuffix

于 2014-02-03T22:05:19.420 回答
91

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.

于 2012-10-23T10:01:18.443 回答
2

这种方式也有效:

var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = TrimRight(filename, extension)

但也许 Paul Ruane 的方法更有效?

于 2013-12-16T07:03:37.660 回答
2

我正在使用 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

文档:https ://golang.org/pkg/path/#Ext

于 2020-06-09T09:21:45.383 回答
1

这是不需要pathor的示例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

https://golang.org/pkg/strings#LastIndexByte

于 2020-11-25T01:05:19.410 回答
0

这只是性能更高的一行。这里是:

filename := strings.Split(file.Filename, ".")[0]
于 2021-09-03T02:43:48.567 回答