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

How to Remove Redundant Spaces from Strings in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 11:24:02528browse

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))
    }
}

Output:

Hello, World !
Hello, World !
Hello, World !

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!

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