Par exemple, j'ai une chaîne de caractères, composée de "sample.zip". Comment puis-je supprimer l'extension ".zip" en utilisant le paquet strings ou autre ?
Réponses
Trop de publicités?
Steven Penny
Points
18523
Voici un exemple qui ne nécessite pas path
o path/filepath
:
func BaseName(s string) string {
n := strings.LastIndexByte(s, '.')
if n == -1 { return s }
return s[:n]
}
et il semble être plus rapide que TrimSuffix
également :
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
Carson Arucard
Points
334
Résumé, y compris en cas de noms d'extension multiples abc.tar.gz et comparaison des performances.
temp_test.go
package _test
import ("fmt";"path/filepath";"strings";"testing";)
func TestGetBasenameWithoutExt(t *testing.T) {
p1 := "abc.txt"
p2 := "abc.tar.gz" // filepath.Ext(p2) return `.gz`
for idx, d := range []struct {
actual interface{}
expected interface{}
}{
{fmt.Sprint(p1[:len(p1)-len(filepath.Ext(p1))]), "abc"},
{fmt.Sprint(strings.TrimSuffix(p1, filepath.Ext(p1))), "abc"},
{fmt.Sprint(strings.TrimSuffix(p2, filepath.Ext(p2))), "abc.tar"},
{fmt.Sprint(p2[:len(p2)-len(filepath.Ext(p2))]), "abc.tar"},
{fmt.Sprint(p2[:len(p2)-len(".tar.gz")]), "abc"},
} {
if d.actual != d.expected {
t.Fatalf("[Error] case: %d", idx)
}
}
}
func BenchmarkGetPureBasenameBySlice(b *testing.B) {
filename := "abc.txt"
for i := 0; i < b.N; i++ {
_ = filename[:len(filename)-len(filepath.Ext(filename))]
}
}
func BenchmarkGetPureBasenameByTrimSuffix(b *testing.B) {
filename := "abc.txt"
for i := 0; i < b.N; i++ {
_ = strings.TrimSuffix(filename, filepath.Ext(filename))
}
}
exécuter cmd : go test temp_test.go -v -bench="^BenchmarkGetPureBasename" -run=TestGetBasenameWithoutExt
sortie
=== RUN TestGetBasenameWithoutExt
--- PASS: TestGetBasenameWithoutExt (0.00s)
goos: windows
goarch: amd64
cpu: Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz
BenchmarkGetPureBasenameBySlice
BenchmarkGetPureBasenameBySlice-8 356602328 3.125 ns/op
BenchmarkGetPureBasenameByTrimSuffix
BenchmarkGetPureBasenameByTrimSuffix-8 224211643 5.359 ns/op
PASS
- Réponses précédentes
- Plus de réponses