Managing whitespace in a string
The string input could contain too much whitespace, too little whitespace, or unsuitable whitespace chars. This recipe includes tips on how to manage these and format the string to your needs.
How to do it...
- Open the console and create the folder
chapter02/recipe11
. - Navigate to the directory.
- Create a file named
whitespace.go
with the following content:
package main import ( "fmt" "math" "regexp" "strconv" "strings" ) func main() { stringToTrim := "\t\t\n Go \tis\t Awesome \t\t" trimResult := strings.TrimSpace(stringToTrim) fmt.Println(trimResult) stringWithSpaces := "\t\t\n Go \tis\n Awesome \t\t" r := regexp.MustCompile("\\s+") replace := r.ReplaceAllString(stringWithSpaces, " ") fmt.Println(replace) needSpace := "need space" fmt.Println(pad(needSpace, 14, "CENTER")) fmt.Println...