patterngoCritical
Trim string's suffix or extension?
Viewed 0 times
stringsuffixextensiontrim
Problem
For example, I have a string, consists of "sample.zip". How do I remove the ".zip" extension using strings package or other else?
Solution
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.
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
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.Code Snippets
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = filename[0:len(filename)-len(extension)]Context
Stack Overflow Q#13027912, score: 101
Revisions (0)
No revisions yet.