BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Trim Spaces

Go 1.23

Cleaning up user input often involves removing whitespace. `strings.TrimSpace` is the go-to tool.

Code

package main

import (
    "fmt"
    "strings"
)

func main() {
    // 1. TrimSpace (Standard)
    // Removes leading and trailing whitespace (spaces, tabs, newlines).
    s := "  	  Hello, Go!   
"
    clean := strings.TrimSpace(s)
    fmt.Printf("TrimSpace: %q\n", clean) // "Hello, Go!"

    // 2. Trim (Custom Cutset)
    // Removes specific characters from both ends.
    // Note: It removes ANY character in the cutset, not the exact string.
    s2 := "!!!Warning!!!"
    clean2 := strings.Trim(s2, "!")
    fmt.Printf("Trim '!': %q\n", clean2) // "Warning"

    // 3. TrimSuffix / TrimPrefix
    // Removes an exact substring from one end.
    file := "image.png"
    name := strings.TrimSuffix(file, ".png")
    fmt.Printf("TrimSuffix: %q\n", name) // "image"
}

Explanation

Sanitizing string input is a frequent requirement, and strings.TrimSpace is the most robust tool for this job. It automatically removes all leading and trailing whitespace characters defined by Unicode, including spaces, tabs, and newlines. This is essential for processing user input where accidental spacing is common.

For more specific needs, strings.Trim allows you to define a "cutset" of characters to remove from the ends of a string. However, a common pitfall is assuming it removes a specific substring; instead, it removes any character found in the cutset. To remove a specific suffix or prefix safely (like a file extension), always use strings.TrimSuffix or strings.TrimPrefix.

  • TrimSpace: Removes all surrounding whitespace.
  • Trim: Removes specific characters from ends.
  • TrimSuffix: Safely removes an exact ending string.

Code Breakdown

12
Using 'strings.TrimSpace'. This is the most common trimming function. It handles tabs ( ) and newlines ( ) automatically, leaving the middle content untouched.
19
Using 'strings.Trim'. We tell it to remove any '!' characters from the start and end. It keeps going until it hits a character that isn't '!'.
25
Using 'strings.TrimSuffix'. This is safer than 'Trim' for removing file extensions because it looks for the exact sequence ".png" only at the end.