package main
import (
"fmt"
"path"
)
func main() {
filename := "device/sdk/CMakeLists.txt"
filenameall := path.Base(filename)
filesuffix := path.Ext(filename)
fileprefix := filenameall[0:len(filenameall) - len(filesuffix)]
//fileprefix, err := strings.TrimSuffix(filenameall, filesuffix)
fmt.Println("file name:", filenameall)
fmt.Println("file prefix:", fileprefix)
fmt.Println("file suffix:", filesuffix)
}
执行结果:
file name: CMakeLists.txt
file prefix: CMakeLists
file suffix: .txt
path.Base(filename)
获取不包含目录的文件名
path.Ext(filename)
获取文件后缀
文件前缀 可以使用切片的方式获取:
fileprefix := filenameall[0:len(filenameall) - len(filesuffix)]
也可以使用 strings.TrimSuffix() 进行获取:
import "strings"
fileprefix, err := strings.TrimSuffix(filenameall, filesuffix)
补充:golang 判断前缀后缀、包含关系
HasPrefix 判断字符串 s 是否以 prefix 开头:
strings.HasPrefix(s, prefix string) bool
HasSuffix 判断字符串 s 是否以 suffix 结尾:
strings.HasSuffix(s, suffix string) bool
字符串包含关系
Contains 判断字符串 s 是否包含 substr :
strings.Contains(s, substr string) bool
测试源码:
package main
import (
"fmt"
"strings"
)
func main() {
var str1 string = "This is an example of a string"
var str2 string = "this is an "
var str3 string = " of a string"
fmt.Println(strings.HasPrefix(str1, str2))
fmt.Println(strings.HasSuffix(str1, str3))
}
运行结果:
[root@localhost golang]# go run zzz.go
false
true
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。如有错误或未考虑完全的地方,望不吝赐教。