×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.TrimFunc() Function with Examples

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

strings.TrimFunc()

The TrimFunc() function is an inbuilt function of strings package that is used to get a string with all leading and trailing Unicode code points c satisfying f(c) removed. It accepts two parameters – a string and function, and returns trimmed string.

Syntax

func TrimFunc(str string, f func(rune) bool) string

Parameters

  • str : The string in which we have to remove leading and trailing Unicode code points.
  • f : The function to be checked the given condition for leading and trailing Unicode code point.

Return Value

The return type of TrimFunc() function is a string, it returns a string with all leading and trailing Unicode code points c satisfying f(c) removed.

Example 1

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

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	// To check space
	f_IsSpace := func(r rune) bool {
		return unicode.IsSpace(r)
	}

	// To check number
	f_IsNumber := func(r rune) bool {
		return unicode.IsNumber(r)
	}
	fmt.Println(strings.TrimFunc("  Hello, world  ", f_IsSpace))
	fmt.Println(strings.TrimFunc("0891Hello, world123", f_IsNumber))
}

Output:

Hello, world
Hello, world

Example 2

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

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	// It will trim leading & trailing all type of
	// Unicode code points except letters and numbers
	f_Trim := func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
	}

	fmt.Println(strings.TrimFunc("  Hello, world  ", f_Trim))
	fmt.Println(strings.TrimFunc("0891Hello, world123", f_Trim))
	fmt.Println(strings.TrimFunc("@@@Hello, world###", f_Trim))
	fmt.Println(strings.TrimFunc("...Hello, world,,,", f_Trim))
	fmt.Println(strings.TrimFunc("  Hello, world!!!", f_Trim))
	fmt.Println(strings.TrimFunc("+++Hello, world===", f_Trim))
}

Output:

Hello, world
0891Hello, world123
Hello, world
Hello, world
Hello, world
Hello, world

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





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