Sep 252019

ADM

How to trim whitespace from string in Golang

  • September 25 2019
  • ADM

 

 

How to trim whitespace from string in Golang - golang

 

The strings package offers a few methods to remove the leading and trailing whitespace from a string.
  • strings.TrimSpace method will remove all the leading and trailing whitespace from a string. The characters that are being removed are '\t', '\n', '\v', '\f', '\r', ' '
  • strings.Trim method will remove the leading and trailing whitespace from a string that are received as parameter.
  • strings.TrimLeft method will remove the leading whitespace from a string that are received as parameter.
  • strings.TrimRight method will remove the trailing whitespace from a string that are received as parameter.

Code

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println("String Trim Example")
	fmt.Println()

	str := "  \t\t\t Test string \n "

	//printing the original string with delimiters to see the actual print
	fmt.Println("Original string")
	fmt.Println("==>" + str + "<==")

	fmt.Println()
	fmt.Println("Trim using strings.TrimSpace function")
	//trimming the spaces, this method will remote the '\t', '\n', '\v', '\f', '\r', ' ' chars
	strTrimSpace := strings.TrimSpace(str)
	fmt.Println("==>" + strTrimSpace + "<==")

	fmt.Println()
	fmt.Println("Trim using strings.Trim function")
	strTrim := strings.Trim(str, "\t \n")
	fmt.Println("==>" + strTrim + "<==")

	fmt.Println()
	fmt.Println("Trim using strings.TrimLeft function")
	strTrimLeft := strings.TrimLeft(str, "\t \n")
	fmt.Println("==>" + strTrimLeft + "<==")

	fmt.Println()
	fmt.Println("Trim using strings.TrimRight function")
	strTrimRight := strings.TrimRight(str, "\t \n")
	fmt.Println("==>" + strTrimRight + "<==")
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build stringTrim.go

Then depending on if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ ./stringTrim

Windows

c:\Users\adm\go\tutorials> stringTrim.exe

If you want to compile and run the application in one single step run the following command:

go run stringTrim.go

Output

String Trim Example

Original string
==>                      Test string
 <==

Trim using strings.TrimSpace function
==>Test string<==

Trim using strings.Trim function
==>Test string<==

Trim using strings.TrimLeft function
==>Test string
 <==

Trim using strings.TrimRight function
==>                      Test string<==

References