To trim a string in Go, you can use the Trim()
function from the strings
package.
In this example,
strings
package.str1
with a value of " Hello World "
.Trim()
function from the strings
package on str1
to remove leading and trailing whitespace characters.package main
import (
"fmt"
"strings"
)
func main() {
str1 := " Hello World "
trimmedStr1 := strings.Trim(str1, " ")
fmt.Printf("Trimmed string is: '%s'\n", trimmedStr1)
}
Trimmed string is: 'Hello World'
In this example,
strings
package.str2
with a value of " apple"
.TrimLeft()
function from the strings
package on str2
to remove leading whitespace characters.package main
import (
"fmt"
"strings"
)
func main() {
str2 := " apple"
trimmedStr2 := strings.TrimLeft(str2, " ")
fmt.Printf("Trimmed string is: '%s'\n", trimmedStr2)
}
Trimmed string is: 'apple'
In this example,
strings
package.str3
with a value of "banana "
.TrimRight()
function from the strings
package on str3
to remove trailing whitespace characters.package main
import (
"fmt"
"strings"
)
func main() {
str3 := "banana "
trimmedStr3 := strings.TrimRight(str3, " ")
fmt.Printf("Trimmed string is: '%s'\n", trimmedStr3)
}
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in Go language with well detailed examples.