golang中如何获取文件的扩展名?
在go的path包里,有func Ext(path string) string方法,这个方法可以获取文件的扩展名,他的返回值是带点.的,比如文件名称是test.txt, 使用这个函数后,返回值是.txt。如果文件没有扩展名,这个方法返回空字符。详情查看源码。
// Ext returns the file name extension used by path.
// The extension is the suffix beginning at the final dot
// in the final slash-separated element of path;
// it is empty if there is no dot.
func Ext(path string) string {
for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- {
if path[i] == '.' {
return path[i:]
}
}
return ""
}
从源码中可以看出,是从字符串的最后一个字符开始遍历,遇到点.结束。如果没有扩展名,则遇到/就结束。最差的情况是把整个字符串都遍历一边。
本文介绍在Go语言中如何使用path包的Ext方法来获取文件的扩展名。该方法从字符串末尾开始查找,遇到第一个点.后停止,返回包含点的扩展名。若文件无扩展名,则返回空字符串。

1200

被折叠的 条评论
为什么被折叠?



