如何在Golang中删除字符串的最后一个字符? [英] How to remove the last character of a string in Golang?

查看:350
本文介绍了如何在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?

推荐答案

以下是删除尾随加号的几种方法.

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

输出:

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

这篇关于如何在Golang中删除字符串的最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆