Home >Backend Development >Golang >How to Efficiently Remove Leading and Trailing Whitespace from Strings in Go?
When handling string variables, it is often necessary to remove any leading (left) or trailing (right) white spaces to ensure data integrity. This process is crucial for maintaining data consistency and avoiding errors in subsequent processing.
To effectively trim both leading and trailing white spaces in Go, the built-in strings.TrimSpace function is highly recommended. It returns a new string with all leading and trailing white spaces removed, while leaving the original string untouched.
To illustrate its usage, let's consider the following code snippet:
package main import ( "fmt" "strings" ) func main() { s := "\t Hello, World\n " fmt.Printf("%d %q\n", len(s), s) t := strings.TrimSpace(s) fmt.Printf("%d %q\n", len(t), t) }
Output:
16 "\t Hello, World\n " 12 "Hello, World"
As you can see, the input string s contains leading (t) and trailing (n ) white spaces, with a length of 16 characters. After using strings.TrimSpace, we obtain a new string t of length 12, with all white spaces removed.
The above is the detailed content of How to Efficiently Remove Leading and Trailing Whitespace from Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!