Home > Backend Development > Golang > How to Efficiently Remove Leading and Trailing Whitespace from Strings in Go?

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

Susan Sarandon
Release: 2024-12-22 05:50:09
Original
333 people have browsed it

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

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:

1

2

16 "\t Hello, World\n "

12 "Hello, World"

Copy after login

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!

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