Micheal Perr
Micheal Perr

Reputation: 1895

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?

Upvotes: 81

Views: 175890

Answers (5)

Brian Sanchez
Brian Sanchez

Reputation: 918

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

go playground:
https://go.dev/play/p/o9ExIEuU0SF

Upvotes: 4

030
030

Reputation: 11679

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

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

package main

import (
    "fmt"
    "strings"
)

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

returns:

Foo+

Upvotes: 45

Shane
Shane

Reputation: 1

@llazzaro

A simple UTF compliant string trimmer is

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

So I'd go with

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

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.

Upvotes: -1

peterSO
peterSO

Reputation: 166598

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 +

Upvotes: 73

jimt
jimt

Reputation: 26410

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

Upvotes: 23

Related Questions