How to Trim a String in Golang?
Last Updated :
05 Nov, 2024
In Go, strings are UTF-8 encoded sequences of variable-width characters, unlike some other languages like Java, python and C++. Go provides several functions within the strings
package to trim characters from strings.In this article we will learn how to Trim a String in Golang.
Example
s := "@@Hello, Geeks!!"
Syntax
func Trim(s string, cutset string) string #Trim
func TrimLeft(s string, cutset string) string # TrimLeft
func TrimRight(s string, cutset string) string # TrimRight
func TrimSpace(s string) string # TrimSpace
func TrimPrefix(s, prefix string) string # TrimPrefix
func TrimSuffix(s, suffix string) string # TrimSuffix
Trim
The Trim
function removes all specified leading and trailing characters from a string.
Syntax
func Trim(s string, cutset string) string
s
: The string to trim.cutset
: Characters to remove from both ends.
Example:
Go
package main
import (
"fmt"
"strings"
)
func main() {
s := "@@Hello, Geeks!!"
result := strings.Trim(s, "@!")
fmt.Println(result)
}
TrimLeft
The TrimLeft
function removes specified characters from the start of a string.
Syntax
func TrimLeft(s string, cutset string) string
Example:
Go
package main
import (
"fmt"
"strings"
)
func main() {
s := "@@Hello, Geeks!!"
result := strings.TrimLeft(s, "@!")
fmt.Println(result)
}
TrimRight
The TrimRight
function removes specified characters from the end of a string.
Syntax
func TrimRight(s string, cutset string) string
Example
Go
package main
import (
"fmt"
"strings"
)
func main() {
s := "@@Hello, Geeks"
result := strings.TrimRight(s, "Geeks")
fmt.Println(result)
}
TrimSpace
The TrimSpace
function removes all leading and trailing whitespace from a string.
Syntax
func TrimSpace(s string) string
Example:
Go
package main
import (
"fmt"
"strings"
)
func main() {
s := " Hello, Geeks "
result := strings.TrimSpace(s)
fmt.Println(result)
}
TrimPrefix
The TrimPrefix
function removes a specified prefix from the beginning of a string if present.
Syntax
func TrimPrefix(s, prefix string) string
Example:
Go
package main
import (
"fmt"
"strings"
)
func main() {
s := "@@Hello, Geeks!!"
result := strings.TrimPrefix(s, "@@")
fmt.Println(result)
}
TrimSuffix
The TrimSuffix
function removes a specified suffix from the end of a string if present.
Syntax
Go
package main
import (
"fmt"
"strings"
)
func main() {
s := "@@Hello, Geeks"
result := strings.TrimSuffix(s, "eeks")
fmt.Println(result)
}