Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Trim prefix 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 TrimPrefix method that can be used to remove a prefix string from the input string. If the input string doesn’t start with the given prefix, 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 TrimPrefix(s, prefix string) string

Let’s look at the working code

Code

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

Output:

removed
tesremoved

Recent Posts

  • Trim leading and trailing whitespaces from a string in Go (Golang)
  • Trim suffix of a string in Go (Golang)
  • Trim prefix of a string in Go (Golang)
  • Capitalize a string in Go (Golang)
  • Convert string to uppercase in Go (Golang)
©2023 Welcome To Golang By Example | Design: Web XP