Trim a String in Golang

In Go, you can trim a string using the strings package, which provides various functions for string manipulation. To trim leading or trailing specific characters or whitespace from a string, you can use strings.Trim(), strings.TrimLeft(), or strings.TrimRight().

Here’s how you can trim a string using strings.Trim():

package main

import (
	"fmt"
	"strings"
)

func main() {
	message := "   Hello, Go!   "
	
	// Trim leading and trailing spaces
	trimmedMessage := strings.Trim(message, " ")
	
	fmt.Println("Original:", message)
	fmt.Println("Trimmed:", trimmedMessage)
}

Output :

Original:    Hello, Go!   
Trimmed: Hello, Go!

In this example, the strings.Trim() function is used to remove leading and trailing spaces from the message string. The second argument to Trim() specifies the characters to be trimmed.

If you only want to trim specific characters from the beginning or end of the string, you can use strings.TrimLeft() or strings.TrimRight() respectively.

// Trim leading "a" characters
trimmedLeft := strings.TrimLeft(message, "a")

// Trim trailing "o" characters
trimmedRight := strings.TrimRight(message, "o")

Remember that these functions create a new string with the specified characters removed; they don’t modify the original string.

Here’s an example demonstrating how to use various functions from the strings package to trim strings in Go:

package main

import (
	"fmt"
	"strings"
)

func main() {
	message := "   Hello, Go!   "
	
	// Trim leading and trailing spaces
	trimmedMessage := strings.Trim(message, " ")

	// Trim leading "H" characters
	trimmedLeft := strings.TrimLeft(message, "H")

	// Trim trailing "!" characters
	trimmedRight := strings.TrimRight(message, "!")

	fmt.Println("Original:", message)
	fmt.Println("Trimmed:", trimmedMessage)
	fmt.Println("Trimmed Left:", trimmedLeft)
	fmt.Println("Trimmed Right:", trimmedRight)
}

Output :

Original:    Hello, Go!   
Trimmed: Hello, Go!
Trimmed Left:    Hello, Go!   
Trimmed Right:    Hello, Go

In this example, we start with the message string that contains leading and trailing spaces. We then use different functions from the strings package to trim spaces, leading “H” characters, and trailing “!” characters. Each function creates a new string with the specified characters removed while leaving the original string unchanged.