To remove all whitespace characters from a string in Go, you can use the strings.ReplaceAll
function in combination with strings.Fields
and strings.Join
.
In this example,
fmt
and strings
packages.removeWhitespace
that takes a string input
as a parameter.strings.Fields
function to split the input string into a slice of substrings, removing any whitespace characters.strings.Join
function to concatenate these substrings into a single string without any whitespace.main
function, we define a string str
with multiple types of whitespace characters.removeWhitespace
function with str
and store the result in the variable result
.result
to standard output.package main
import (
"fmt"
"strings"
)
func removeWhitespace(input string) string {
return strings.Join(strings.Fields(input), "")
}
func main() {
str := " Hello \t World \n with \t mixed \n whitespace "
result := removeWhitespace(str)
fmt.Println("String without whitespace:", result)
}
String without whitespace: HelloWorldwithmixedwhitespace
In this example,
fmt
and strings
packages.removeWhitespace
function that takes a string input
as a parameter.strings.Fields
to split the input string into a slice of substrings, removing any whitespace characters.strings.Join
to concatenate these substrings into a single string without any whitespace.main
function, we define a different string str
with various whitespace characters.removeWhitespace
function with str
and store the result in the variable result
.result
to standard output.package main
import (
"fmt"
"strings"
)
func removeWhitespace(input string) string {
return strings.Join(strings.Fields(input), "")
}
func main() {
str := "Go \n is \t awesome \t\n and \n fast"
result := removeWhitespace(str)
fmt.Println("String without whitespace:", result)
}
String without whitespace: Goisawesomeandfast
In this tutorial, we learned How to Remove All Whitespace Characters from a String in Go language with well detailed examples.