Trim()

4hbab's avatar
Published Jul 8, 2023
Contribute to Docs

The Trim() function removes leading and trailing characters from a string based on the given input. The strings library must be imported in order to use this function.

Syntax

trimmed := strings.Trim(str, cutset)

Where:

  • str: The input string from which the leading and trailing characters are to be removed.
  • cutset: The string containing the characters to be removed.
  • trimmed: The resulting string after trimming.

Example

The following removes leading and trailing whitespace characters from a string and prints the result:

package main
import (
"fmt"
"strings"
)
func main() {
str := " Hello, World! "
trimmed := strings.Trim(str, " ")
fmt.Println(trimmed)
}

The output will be:

Hello, World!

Codebyte Example

The following runnable example uses the Trim() function to remove specific characters from a string:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Go on Codecademy