The Trim() Function is used to remove any unwanted character from the String.
package main
import "fmt"
import "strings"
func main() {
x := " Hello "
y := strings.Trim(x," ")
fmt.Println(y)
}
In the above code, we have declared a String ' Hello ' with leading and trailing spaces.
-Function1.png)
Then we have used the 'Trim()' function to remove any unwanted spaces from beginning and end.
-Function2.png)
Unwanted spaces are stripped out of it.
Now, let us say you want have asterisk '*' in front of the String and after the String. And you want to remove them.
package main
import "fmt"
import "strings"
func main() {
x := "***Hello**"
y := strings.Trim(x,"*")
fmt.Println(y)
}
In the above code, we have declared a String ' Hello ' with leading and trailing asterisk '*'.
-Function3.png)
Then we have used the 'Trim()' function to remove any asterisk '*' from beginning and end.
-Function2.png)
And asterisk '*' are stripped out of it.