How to remove the last character of a string in Golang?

后端 未结 4 978
时光说笑
时光说笑 2021-02-03 17:43

I want to remove the very last character of a string, but before I do so I want to check if the last character is a \"+\". How can this be done?

4条回答
  •  醉酒成梦
    2021-02-03 17:58

    Here are several ways to remove trailing plus sign(s).

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func TrimSuffix(s, suffix string) string {
        if strings.HasSuffix(s, suffix) {
            s = s[:len(s)-len(suffix)]
        }
        return s
    }
    
    func main() {
        s := "a string ++"
        fmt.Println("s: ", s)
    
        // Trim one trailing '+'.
        s1 := s
        if last := len(s1) - 1; last >= 0 && s1[last] == '+' {
            s1 = s1[:last]
        }
        fmt.Println("s1:", s1)
    
        // Trim all trailing '+'.
        s2 := s
        s2 = strings.TrimRight(s2, "+")
        fmt.Println("s2:", s2)
    
        // Trim suffix "+".
        s3 := s
        s3 = TrimSuffix(s3, "+")
        fmt.Println("s3:", s3)
    }
    

    Output:

    s:  a string ++
    s1: a string +
    s2: a string 
    s3: a string +
    

提交回复
热议问题