25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Trimming Whitespace from Strings in Go
Code Snippet

Trimming Whitespace from Strings in Go

go

Go provides several string trimming functions in the strings package to remove leading and trailing characters. The TrimSpace function is the most commonly used, as it removes all leading and trailing whitespace characters including spaces, tabs, and newlines.

For more granular control, you can use Trim, which removes any characters from a specified set. The TrimLeft and TrimRight functions remove characters only from the left or right side of the string respectively. Here’s an example showing different trimming approaches:

package main

import (
  "fmt"
  "strings"
)

func main() {
  // TrimSpace removes all leading and trailing whitespace
  str1 := "  hello world  "
  fmt.Println(strings.TrimSpace(str1)) // Output: hello world

  // Trim removes specified characters from both sides
  str2 := "###hello###"
  fmt.Println(strings.Trim(str2, "#")) // Output: hello

  // TrimLeft removes from the left side only
  str3 := ">>>text"
  fmt.Println(strings.TrimLeft(str3, ">")) // Output: text

  // TrimRight removes from the right side only
  str4 := "data..."
  fmt.Println(strings.TrimRight(str4, ".")) // Output: data
}

Understanding string trimming is essential for cleaning user input, parsing data files, and preparing strings for further processing. The choice between these functions depends on what characters you want to remove and from which side of the string.

Further Reading:

If you found this snippet useful, you may also enjoy some of the other content on the site: