亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從字符串中刪除最后 4 個字符?

如何從字符串中刪除最后 4 個字符?

Go
料青山看我應如是 2023-06-19 15:38:09
我想從字符串中刪除最后 4 個字符,所以“test.txt”變成了“test”。package mainimport (    "fmt"    "strings")func main() {    file := "test.txt"    fmt.Print(strings.TrimSuffix(file, "."))}
查看完整描述

3 回答

?
夢里花落0921

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'

                                         -> ''


查看完整回答
反對 回復 2023-06-19
?
哈士奇WWW

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)))


查看完整回答
反對 回復 2023-06-19
?
偶然的你

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

}


查看完整回答
反對 回復 2023-06-19
  • 3 回答
  • 0 關注
  • 262 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號