Home >Backend Development >Golang >How to Efficiently Trim Leading and Trailing Whitespace from a Go String?

How to Efficiently Trim Leading and Trailing Whitespace from a Go String?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 21:19:10263browse

How to Efficiently Trim Leading and Trailing Whitespace from a Go String?

Trimming Leading and Trailing White Spaces in a Go String

In Go, strings can contain leading and trailing whitespace characters, such as spaces and tabs. Trimming these superfluous spaces can improve code readability and functionality. The most efficient approach to achieve this in Go is through the strings.TrimSpace function.

Using strings.TrimSpace(s)

The strings.TrimSpace(s) function takes a string s as input and returns a new string with all leading and trailing whitespace characters removed. It does not affect the original string s.

The syntax for strings.TrimSpace is:

func TrimSpace(s string) string

Example

Consider the following code:

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"

In this example, the string s contains leading whitespace characters (a tab) and trailing whitespace characters (a newline and a space). The strings.TrimSpace(s) function removes all these characters, resulting in the trimmed string t.

The len function is used to illustrate the reduction in string length after trimming the whitespace.

The above is the detailed content of How to Efficiently Trim Leading and Trailing Whitespace from a Go String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn