Trim a string in Go Language - Examples
Hello everyone, In this tutorial, we will show you how to trim all of the leading and trailing spaces in a string.
Few methods from the strings package are,
- Trim():
- TrimSpace()
- TrimLeft()
- TrimRight()
- TrimPrefix()
- TrimSuffix()
Example 1: strings.Trim() function
The Trim() function is an inbuilt method of the strings package. This method will remove the leading and trailing whitespace from a string that is received as a parameter.
// Golang program to demonstrate the
// example of strings.Trim() Method
package main
import (
"fmt"
"strings"
)
func main() {
str1 := " My world is too small "
fmt.Println("Before:", str1)
str4 := strings.Trim(str1, " ")
fmt.Println("After:", str4)
}
Output:
Example 2: strings.TrimSpace() function
The TrimSpace() function is an inbuilt method of the strings package. This is a better choice if a variety of whitespace runes may be present at the start or end of a string.For example, '\t', '\n', '\v', '\f', '\r', ' '
// Golang program to demonstrate the
// example of strings.TrimSpace() Method
package main
import (
"fmt"
"strings"
)
func main() {
str1 := " \t My world is too small"
fmt.Println("Before:", str1)
str4 := strings.TrimSpace(str1)
fmt.Println("After:", str4)
}
Output:
Example 3: strings.TrimLeft() function
The TrimLeft() method will remove the leading whitespace from a string that is received as a parameter.
// Golang program to demonstrate the
// example of strings.TrimLeft() Method
package main
import (
"fmt"
"strings"
)
func main() {
str1 := " My world is too small "
fmt.Println("Before:", str1)
str4 := strings.TrimLeft(str1, " ")
fmt.Println("After:", str4)
}
Output:
Example 4: strings.TrimRight() function
The TrimRight() method will remove the trailing whitespace from a string that is received as a parameter.
// Golang program to demonstrate the
// example of strings.TrimRight() Method
package main
import (
"fmt"
"strings"
)
func main() {
str1 := " My world is too small "
fmt.Println("Before:", str1)
str4 := strings.TrimRight(str1, " ")
fmt.Println("After:", str4)
}
Output:
Example 5: strings.TrimPrefix() function
The TrimPrefix() method will remove the prefix from a string that is received as a parameter.
// Golang program to demonstrate the
// example of strings.TrimPrefix() Method
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "http://knowledgefactory.net"
fmt.Println("Before:", str1)
str4 := strings.TrimPrefix(str1, "http://")
fmt.Println("After:", str4)
}
Output:
Example 6: strings.TrimSuffix() function
The TrimSuffix() method will remove the suffix from a string that is received as a parameter.
// Golang program to demonstrate the
// example of strings.TrimSuffix() Method
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "http://knowledgefactory.net.com"
fmt.Println("Before:", str1)
str4 := strings.TrimSuffix(str1, ".com")
fmt.Println("After:", str4)
}
Output: