Go 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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours

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

All contributors

Contribute to Docs

Learn Go on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours