Golang strings.Trim() Function with Examples

Golang | strings.Trim() Function: Here, we are going to learn about the Trim() function of strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 23, 2021

strings.Trim()

The Trim() function is an inbuilt function of strings package which is used to get a string with all specified leading and trailing Unicode code points removed. It accepts two parameters – a string and a cutset string, and returns trimmed string.

Syntax:

func Trim(str, cutset string) string

Parameter(s):

  • str : The string in which we have to remove leading and trailing Unicode code points.
  • cutset : The string (a set of characters / Unicode code points) to be trimmed.

Return Value:

The return type of Trim() function is a string, it returns a string with all specified leading and trailing Unicode code points removed.

Example 1:

// Golang program to demonstrate the
// example of strings.Trim() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Trim("  Hello, world  ", " "))
	fmt.Println(strings.Trim("  Hello,   world  ", " "))
	fmt.Println(strings.Trim("...Hello, world...", "."))
	fmt.Println(strings.Trim("###Hello, world!!!", "#"))
	fmt.Println(strings.Trim("###Hello, world!!!", "!"))
	fmt.Println(strings.Trim("###Hello, world!!!", "#!"))
}

Output:

Hello, world
Hello,   world
Hello, world
Hello, world!!!
###Hello, world
Hello, world

Example 2:

// Golang program to demonstrate the
// example of strings.Trim() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string
	var result string

	str = "***Hi, there! How are you?*"
	result = strings.Trim(str, "*")
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "'Hi, how are you?"
	result = strings.Trim(str, "'?")
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "¡¡¡Hello, world!!!"
	result = strings.Trim(str, "¡!")
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)
}

Output:

Actual string : ***Hi, there! How are you?*
Trimmed string: Hi, there! How are you?
Actual string : 'Hi, how are you?
Trimmed string: Hi, how are you
Actual string : ¡¡¡Hello, world!!!
Trimmed string: Hello, world

Golang strings Package Functions »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.