简体   繁体   English

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

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

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?如何才能做到这一点?

Builtin function is available now. 内置功能现在可用。 http://golang.org/pkg/strings/#TrimSuffix http://golang.org/pkg/strings/#TrimSuffix

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 +

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]
}

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+
package main

import (
    "fmt"
)

func main() {

    s := "venga|ese|sabor|"
    newString := ""
    if len(s) > 0 {
        newString = s[:len(s)-1]
    }
    fmt.Println(newString)
}

output: venga|ese|sabor output: 文加|塞|萨博

go playground: go游乐场:
https://go.dev/play/p/o9ExIEuU0SF https://go.dev/play/p/o9ExIEuU0SF

@llazzaro @llazzaro

A simple UTF compliant string trimmer is一个简单的 UTF 兼容字符串修剪器是

string([]rune(foo)[:len(foo)-1]))

So I'd go with所以我会用 go

f2 := []rune(foo)
for f2[len(f2)-1] == '+'{
    f2 = f2[:len(f2)-1]
}
foo = string(f2)

https://go.dev/play/p/anOwXlfQWaF https://go.dev/play/p/anOwXlfQWaF

I'm not sure why the other answers trimmed the way that they do, because they're trimming bytes.我不确定为什么其他答案会像他们那样修剪,因为它们正在修剪字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM