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

Hi 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

  1. Create a sample string variable and store some data
  2. Use strings.TrimSuffix() method to remove last character
  3. 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.

remove, last character of a string, golang

Try it yourself

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 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts