string 如何在Golang中删除字符串的最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8689425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:19:41  来源:igfitidea点击:

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

stringgo

提问by Micheal Perr

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?

我想删除字符串的最后一个字符,但在此之前我想检查最后一个字符是否为“+”。如何才能做到这一点?

回答by Karthik G R

Builtin function is available now. http://golang.org/pkg/strings/#TrimSuffix

内置功能现已可用。 http://golang.org/pkg/strings/#TrimSuffix

回答by peterSO

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 +

回答by jimt

No builtin way. But it's trivial to do manually.

没有内置方式。但是手动操作很简单。

s := "mystring+"
sz := len(s)

if sz > 0 && s[sz-1] == '+' {
    s = s[:sz-1]
}

回答by 030

Based on the answer of @KarthikGR the following example was added:

根据@KarthikGR 的回答,添加了以下示例:

https://play.golang.org/p/ekDeT02ZXoq

https://play.golang.org/p/ekDeT02ZXoq

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.TrimSuffix("Foo++", "+"))
}

returns:

返回:

Foo+