我想从字符串中删除最后4个字符,因此“ test.txt”变为“ test”。
package main
import (
"fmt"
"strings"
)
func main() {
file := "test.txt"
fmt.Print(strings.TrimSuffix(file, "."))
}
您可以使用它删除最后一个“。”之后的所有内容。
去操场
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句