Go: Remove duplicate whitespace from a string
space := regexp.MustCompile(`\s+`)
str := space.ReplaceAllString("Hello \t \n world!", " ")
fmt.Println(str) // "Hello world!"
\s+ is a regular expression. The character class \s matches a space, tab, new line, carriage return or form feed, and + says “one or more of those”. In other words, the code will replace all whitespace substrings with a single space character.
Comments
Be the first to comment!