'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?
Solution 1:[1]
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+
Solution 2:[2]
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]
}
Solution 3:[3]
@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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jimt |
| Solution 3 | Shane |
