How to remove multiple spaces in a string in GoLang?
Removing multiple spaces from a string excludes excessive white space so that there is only a single space between each word in the string.
Remove Multiple Spaces
Example
// Golang program to remove
// multiple white-spaces from string
package main
import (
"fmt"
"strings"
)
func standardizeSpaces(s string) string {
return strings.Join(strings.Fields(s), " ")
}
func main() {
str1 := " Hello, World ! "
fmt.Println(standardizeSpaces(str1))
str2 := "Hello,\tWorld ! "
fmt.Println(standardizeSpaces(str2))
str3 := " \t\n\t Hello,\tWorld\n!\n\t"
fmt.Println(standardizeSpaces(str3))
}
Output
Hello, World !
Hello, World !
Hello, World !
Most Helpful This Week
Golang Slice interface and array concatenationHow to include and execute HTML template?Replace numbers by zero from stringHow to add Watermark or Merge two image?Example of Sscan vs Sscanf vs Sscanln from FMT PackageCopy an array by value and reference into another arrayConvert Int data type to Int16 Int32 Int64How to check if a string contains a white space in Golang?Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.How to check if a string contains a numbers in Golang?