string 修剪字符串的后缀或扩展名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13027912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trim string's suffix or extension?
提问by Coder
For example, I have a string, consists of "sample.zip". How do I remove the ".zip" extension using strings package or other else?
例如,我有一个字符串,由“sample.zip”组成。如何使用字符串包或其他方式删除“.zip”扩展名?
回答by Keith Cascio
回答by Paul Ruane
Edit: Go has moved on. Please see Keith's answer.
编辑:Go 继续前进。请参阅基思的回答。
Use path/filepath.Extto get the extension. You can then use the length of the extension to retrieve the substring minus the extension.
使用path/filepath.Ext获取扩展名。然后,您可以使用扩展名的长度来检索减去扩展名的子字符串。
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = filename[0:len(filename)-len(extension)]
Alternatively you could use strings.LastIndexto 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.
或者,您可以使用strings.LastIndex来查找最后一个句点 (.) 但这可能会更加脆弱,因为会有一些边缘情况(例如没有扩展名)filepath.Ext
处理您可能需要明确编码的情况,或者如果 Go 是在使用除句点以外的扩展分隔符的理论 O/S 上运行。
回答by Allan Ruin
This way works too:
这种方式也有效:
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = TrimRight(filename, extension)
but maybe Paul Ruane's method is more efficient?
但也许 Paul Ruane 的方法更有效?