Wednesday, November 27, 2019

How to trim spaces, new line and return line characters in Go language?

I have answered this in StackOverflow too.
Please visit the answer.

Here is the solutions:

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))
test := "pdftk 2.02 a Handy Tool for Manipulating PDF Documents\nCopyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com\nThis is free software; see the source code for copying conditions. There is\nNO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
fmt.Println(test)
strArray := strings.Split(test, "\n")
fmt.Println(strArray)
result = strings.Replace(test, "\n", " ", -1)
fmt.Println(result)
}