如何从字符串中删除最后4个字符?

4
我想从一个字符串中删除最后4个字符,因此"test.txt"变成了"test"。
package main

import (
    "fmt"
    "strings"
)

func main() {
    file := "test.txt"
    fmt.Print(strings.TrimSuffix(file, "."))
}
3个回答

5
这将安全地删除任何点扩展名,并且如果未找到扩展名,则会容忍:
func removeExtension(fpath string) string {
        ext := filepath.Ext(fpath)
        return strings.TrimSuffix(fpath, ext)
}

示例代码: Playground.

表格测试:

/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'
                                         -> ''

4
虽然已经有一个被接受的答案,但我想分享一些用于字符串操作的切片技巧。
  1. Remove last n characters from a string

    As the title says, remove the last 4 characters from a string, it is very common usage of slices, ie,

    file := "test.txt"
    fmt.Println(file[:len(file)-4]) // you can replace 4 with any n
    

    Output:

    test
    

    Playground example.

  2. Remove file extensions:

    From your problem description, it looks like you are trying to trim the file extension suffix (ie, .txt) from the string.

    For this, I would prefer @colminator's answer from above, which is

    file := "test.txt"
    fmt.Println(strings.TrimSuffix(file, filepath.Ext(file)))
    

0

您可以使用此方法删除最后一个 "." 之后的所有内容。
go playground

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
}

请记得检查字符串中是否存在该字符。另外,点号也可能出现在目录名称中,因此如果您正在检查路径而不是文件名,则应调整此代码。 - boreq
这段程序会在没有点的文件中引发panic:https://play.golang.org/p/EZit4VT16OU - colm.anseo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接