Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Trim suffix of a string in Go (Golang)

Posted on March 11, 2023March 11, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a TrimSuffix method that can be used to remove a suffix string from the input string. If the input string doesn’t end with the given suffix, then the input string remains unchanged. Also, note that this function returns the copy of the string.

Below is the signature of the function

func TrimSuffix(s, suffix string)

Let’s look at the working code

Code:

package main
import (
"fmt"
"strings"
)
func main() {
//This will output "removed"
res := strings.TrimSuffix("removedtest", "test")
fmt.Println(res)
//The input string will remain unchanged as it doesn't contain the test as suffix
res2 := strings.TrimSuffix("removedtes", "test")
fmt.Println(res2)
}

Output:

removed
removedtes

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2024 Welcome To Golang By Example | Design: Web XP