How to remove all leading and trailing whitespaces in Go
The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
It provides the TrimSpace() method, which can be used to remove all leading and trailing whitespaces from the input string.
Syntax
func TrimSpace(s string) string
Arguments
-
It takes the
sstring as input. -
It returns a slice of the
sstring with all leading and trailing whitespaces removed.
Code
In the code below, we have first imported the fmt and strings package to our program.
package mainimport ("fmt""strings")func main() {str1 := "\n\t\t Educative IO \t \t "str2 := "\t\tMultiple whitespaces \n\t\t\n"fmt.Println("String Before:" + str1)fmt.Println("String After TrimSpace():"+ strings.TrimSpace(str1))fmt.Println("String Before:" + str2)fmt.Println("String After TrimSpace():"+ strings.TrimSpace(str2))}
Explanation
After importing, we call the TrimSpace() method with "\n\t\t Educative IO \t \t " as the input string. This returns "Educative IO" after all the leading and trailing tabs and spaces are removed.
We again call the TrimSpace() method with "\t\tMultiple whitespaces \n\t\t\n" as the input string. This returns "Multiple whitespaces" after all the leading and trailing newlines, tabs, and spaces are removed.
We can observe that the spaces in the middle of the string are not removed.
To show the output of all these operations, we use the Println() method of the fmt package.
Output
The program prints the output below and exits.
String Before:
Educative IO
String After TrimSpace():Educative IO
String Before: Multiple whitespaces
String After TrimSpace():Multiple whitespaces