How to trim leading and trailing white spaces of a string?

Go

Go Problem Overview


Which is the effective way to trim the leading and trailing white spaces of string variable in Go?

Go Solutions


Solution 1 - Go

strings.TrimSpace(s)

For example,

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "\t Hello, World\n "
	fmt.Printf("%d %q\n", len(s), s)
	t := strings.TrimSpace(s)
	fmt.Printf("%d %q\n", len(t), t)
}

Output:

16 "\t Hello, World\n "
12 "Hello, World"

Solution 2 - Go

There's a bunch of functions to trim strings in go.

See them there : Trim

Here's an example, adapted from the documentation, removing leading and trailing white spaces :

fmt.Printf("[%q]", strings.Trim(" Achtung  ", " "))

Solution 3 - Go

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}

> Output: > Hello, Gophers

And simply follow this link - https://golang.org/pkg/strings/#TrimSpace

Solution 4 - Go

For trimming your string, Go's "strings" package have TrimSpace(), Trim() function that trims leading and trailing spaces.

Check the documentation for more information.

Solution 5 - Go

Just as @Kabeer has mentioned, you can use TrimSpace and here is an example from golang documentation:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}

Solution 6 - Go

@peterSO has correct answer. I am adding more examples here:

package main

import (
	"fmt"
	strings "strings"
)

func main() { 
	test := "\t pdftk 2.0.2  \n"
	result := strings.TrimSpace(test)
	fmt.Printf("Length of %q is %d\n", test, len(test))
	fmt.Printf("Length of %q is %d\n\n", result, len(result))
	
	test = "\n\r pdftk 2.0.2 \n\r"
	result = strings.TrimSpace(test)
	fmt.Printf("Length of %q is %d\n", test, len(test))
	fmt.Printf("Length of %q is %d\n\n", result, len(result))
	
	test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
	result = strings.TrimSpace(test)
	fmt.Printf("Length of %q is %d\n", test, len(test))
	fmt.Printf("Length of %q is %d\n\n", result, len(result))
	
	test = "\r pdftk 2.0.2 \r"
	result = strings.TrimSpace(test)
	fmt.Printf("Length of %q is %d\n", test, len(test))
	fmt.Printf("Length of %q is %d\n\n", result, len(result))	
}

You can find this in Go lang playground too.

Solution 7 - Go

A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.

(example: the string value of {"first_name":" I have whitespace "} will convert to "\" I have whitespace \"")

Before you can trim anything, you'll need to remove the extra quotes first:

playground example

// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string

// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
	ns := string(data)
	// Make sure we don't have a blank string of "\"\"".
	if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
		*s = ""
		return nil
	}
	// Remove the added wrapping quotes.
	ns, err := strconv.Unquote(ns)
	if err != nil {
		return err
	}
	// We can now trim the whitespace.
	*s = ScrubString(strings.TrimSpace(ns))

	return nil
}

Solution 8 - Go

I was interested in performance, so I did a comparison of just trimming the left side:

package main

import (
   "strings"
   "testing"
)

var s = strings.Repeat("A", 63) + "B"

func BenchmarkTrimLeftFunc(b *testing.B) {
   for n := 0; n < b.N; n++ {
      _ = strings.TrimLeftFunc(s, func(r rune) bool {
         return r == 'A'
      })
   }
}

func BenchmarkIndexFunc(b *testing.B) {
   for n := 0; n < b.N; n++ {
      i := strings.IndexFunc(s, func(r rune) bool {
         return r != 'A'
      })
      _ = s[i]
   }
}

func BenchmarkTrimLeft(b *testing.B) {
   for n := 0; n < b.N; n++ {
      _ = strings.TrimLeft(s, "A")
   }
}

TrimLeftFunc and IndexFunc are the same, with TrimLeft being slower:

BenchmarkTrimLeftFunc-12        10325200               116.0 ns/op
BenchmarkIndexFunc-12           10344336               116.6 ns/op
BenchmarkTrimLeft-12             6485059               183.6 ns/op

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex MathewView Question on Stackoverflow
Solution 1 - GopeterSOView Answer on Stackoverflow
Solution 2 - GoDenys SéguretView Answer on Stackoverflow
Solution 3 - GoNikta JnView Answer on Stackoverflow
Solution 4 - GoKabeer ShaikhView Answer on Stackoverflow
Solution 5 - GoNanthini MuniapanView Answer on Stackoverflow
Solution 6 - GoS.MishraView Answer on Stackoverflow
Solution 7 - GoskplunkerinView Answer on Stackoverflow
Solution 8 - GoZomboView Answer on Stackoverflow