"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Go language efficiently removes whitespace characters before and after strings

Go language efficiently removes whitespace characters before and after strings

Posted on 2025-05-03
Browse:139

How to Efficiently Remove Leading and Trailing Whitespace from Strings in Go?

Removing Leading and Trailing White Spaces 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.

Efficient Trimming Using 'strings.TrimSpace'

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.

Example

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.

Latest tutorial More>

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