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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3