3 回答

TA貢獻1772條經驗 獲得超6個贊
這將安全地刪除任何點擴展 - 如果沒有找到擴展將是容忍的:
func removeExtension(fpath string) string {
ext := filepath.Ext(fpath)
return strings.TrimSuffix(fpath, ext)
}
游樂場示例。
表測試:
/www/main.js -> '/www/main'
/tmp/test.txt -> '/tmp/test'
/tmp/test2.text -> '/tmp/test2'
/tmp/test3.verylongext -> '/tmp/test3'
/user/bob.smith/has.many.dots.exe -> '/user/bob.smith/has.many.dots'
/tmp/zeroext. -> '/tmp/zeroext'
/tmp/noext -> '/tmp/noext'
-> ''

TA貢獻1799條經驗 獲得超6個贊
雖然已經有一個公認的答案,但我想分享一些字符串操作的切片技巧。
從字符串中刪除最后 n 個字符
正如標題所說,remove the last 4 characters from a string,這是非常常見的用法slices,即,
file := "test.txt"
fmt.Println(file[:len(file)-4]) // you can replace 4 with any n
輸出:
test
游樂場示例。
刪除文件擴展名:
從您的問題描述來看,您似乎正試圖.txt從字符串中刪除文件擴展名后綴(即 )。
為此,我更喜歡上面@colminator 的回答,即
file := "test.txt"
fmt.Println(strings.TrimSuffix(file, filepath.Ext(file)))

TA貢獻1841條經驗 獲得超3個贊
您可以使用它來刪除最后一個“。”之后的所有內容。
去游樂場
package main
import (
"fmt"
"strings"
)
func main() {
sampleInput := []string{
"/www/main.js",
"/tmp/test.txt",
"/tmp/test2.text",
"/tmp/test3.verylongext",
"/user/bob.smith/has.many.dots.exe",
"/tmp/zeroext.",
"/tmp/noext",
"",
"tldr",
}
for _, str := range sampleInput {
fmt.Println(removeExtn(str))
}
}
func removeExtn(input string) string {
if len(input) > 0 {
if i := strings.LastIndex(input, "."); i > 0 {
input = input[:i]
}
}
return input
}
- 3 回答
- 0 關注
- 262 瀏覽
添加回答
舉報