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

后端 未结 7 1331
别那么骄傲
别那么骄傲 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:35

    @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.

    0 讨论(0)
提交回复
热议问题