How to remove the last character of a string in Golang?
May 27, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
Today, I’m going to show how do you remove the last character of a string in Golang, here I will use the golang built-in function TrimSuffix()
method to remove the last char.
The TrimSuffix returns s without the provided trailing suffix string. If s doesn’t end with a suffix, s is returned unchanged.
Let’s start today’s tutorial How to remove the last character of a string in Golang?
In the following example, I’m going to do
- Create a sample string variable and store some data
- Use
strings.TrimSuffix()
method to remove last character - Print the output after using
strings.TrimSuffix()
package main
import (
"fmt"
"strings"
)
func main() {
var s = "¡¡¡Hello, Gophers!!!"
s = strings.TrimSuffix(s, ", Gophers!!!")
s = strings.TrimSuffix(s, ", Marmots!!!")
fmt.Print(s)
}
When you run the above program, it will print ¡¡¡Hello
let’s check the output.
After understanding the above example, we know if the string does not match with the last character it will return the string unchanged.
All the best 👍