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

后端 未结 7 1330
别那么骄傲
别那么骄傲 2021-01-30 02:56

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

相关标签:
7条回答
  • 2021-01-30 03:08

    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"))
    }
    
    0 讨论(0)
  • 2021-01-30 03:13
    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

    0 讨论(0)
  • 2021-01-30 03:28

    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
    }
    
    0 讨论(0)
  • 2021-01-30 03:30

    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  ", " "))
    
    0 讨论(0)
  • 2021-01-30 03:31

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

    Check the documentation for more information.

    0 讨论(0)
  • 2021-01-30 03:34

    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"
    
    0 讨论(0)
提交回复
热议问题