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
Release: 2024-12-02 21:19:10
Original
267 people have browsed it

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
Copy after login

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)
}
Copy after login

Output:

16 "\t Hello, World\n "
12 "Hello, World"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template