示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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)
获取文件后缀
文件前缀 可以使用切片的方式获取:
1
|
fileprefix := filenameall[0:len(filenameall) - len(filesuffix)]
|
也可以使用 strings.TrimSuffix() 进行获取:
1
2
|
import "strings"
fileprefix, err := strings.TrimSuffix(filenameall, filesuffix)
|
补充:golang 判断前缀后缀、包含关系
HasPrefix 判断字符串 s 是否以 prefix 开头:
1
|
strings.HasPrefix(s, prefix string) bool
|
HasSuffix 判断字符串 s 是否以 suffix 结尾:
1
|
strings.HasSuffix(s, suffix string) bool
|
字符串包含关系
Contains 判断字符串 s 是否包含 substr :
1
|
strings.Contains(s, substr string) bool
|
测试源码:
1
2
3
4
5
6
7
8
9
10
11
12
|
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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://zhuanlan.zhihu.com/p/80403583