OneBite.Dev - Coding blog in a bite size

trim a string in Go

Code snippet on how to trim a string in Go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := " Hi, I am a string "
	strTrimmed := strings.TrimSpace(str)
	fmt.Println(strTrimmed)
}

This code is written in the Go programming language and it will trim the whitespace from a given string. The code starts with a package declaration, which is required for every Go program. It then imports two external packages, fmt and strings, which provides some useful functions related to strings. The main function is then called, where a string with whitespace is stored in a variable called str. The TrimSpace function from the strings package is then called to trim the whitespace from the string. Finally, the trimmed string is printed using the fmt package.

go