Home > Backend Development > Golang > How to Remove Redundant Spaces from Strings in Go?

How to Remove Redundant Spaces from Strings in Go?

Mary-Kate Olsen
Release: 2024-11-10 11:24:02
Original
569 people have browsed it

How to Remove Redundant Spaces from Strings in Go?

Removing Redundant Spaces from Strings in Go

In Go, you may encounter situations where you need to clean up strings by removing unnecessary whitespace or spaces. This involves removing leading and trailing whitespace, newlines, null characters, and excessive spaces within the string.

Using Strings Package for Basic Standardization

For basic whitespace standardization, the strings package offers a convenient solution:

package main

import (
    "fmt"
    "strings"
)

func standardizeSpaces(s string) string {
    return strings.Join(strings.Fields(s), " ")
}

func main() {
    tests := []string{" Hello,   World  ! ", "Hello,\tWorld ! ", " \t\n\t Hello,\tWorld\n!\n\t"}
    for _, test := range tests {
        fmt.Println(standardizeSpaces(test))
    }
}
Copy after login

Output:

Hello, World !
Hello, World !
Hello, World !
Copy after login

This function removes leading and trailing whitespace, as well as any consecutive spaces within the string. However, it does not handle international space characters or null characters.

The above is the detailed content of How to Remove Redundant Spaces from Strings in Go?. 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