Although a specific language can define what makes up a white-space character, the above are the universal white-space character as defined in the Unicode Character set (used by most programming languages).
In this guide, though, we will focus on removing whitespace characters from a string in the go programming language.
Introduction
Using various methods from the strings package, removing white-space characters from a string is very easy.
Let us discuss these methods and how we can remove white spaces.
Strings.TrimSpace()
The TrimSpace() method from the strings package allows you to remove leading and trailing white-space characters from a specified string. The function removes the following white-space characters as defined by Unicode:
- \t – tab character
- \ n – Line break character
- \v – Vertical Tab character
- \r – Carriage return
- \f – Form feed character
The function syntax is as shown:
The function takes the string to trim as the argument and returns a slice of the string with all the leading and trailing white spaces removed.
Consider the example string below:
If we print the above string:
♀ ♂
To remove the leading and trailing whitespaces using the TrimSpace() function, we can do:
import (
"fmt"
"strings"
)
funcmain() {
str := "\t \r Hello from LinuxHint \n \f \v"
str = strings.TrimSpace(str)
fmt.Println(str)
}
The above function returns the string with no whitespace, as shown in the output below:
Strings.Trim()
You will notice that the TrimSpace() function does not accept the type of white space to remove. This is where the Trim() functions. It works similarly to the TrimeSpace() function but allows you to specify the character to remove.
Let us take the example string above:
To remove the \t, \f, and \v characters, we can do:
import (
"fmt"
"strings"
)
funcmain() {
str := "\t \r Hello from LinuxHint \n \f \v"
str = strings.Trim(str, "\t \f \v")
fmt.Println(str)
}
Here, we remove the desired characters leaving other white-space characters. The resulting string is as:
What if you need to remove white space from either side of the string?
Strings.TrimLeft & Strings.TrimRight()
The TrimSpace() and Trim() methods remove leading and trailing characters. However, we can use the TrimLeft() and TrimRight() methods to remove white-space characters on the left and right side of the string, respectively.
To remove the white spaces on the left of the string, we can do:
str = strings.TrimLeft(str, "\t")
To remove white-space on the right of the string, we can do:
str = strings.TrimRight(str, "\f \v")
Both functions accept the type of character to remove from the string.
Conclusion
This guide covered several methods and techniques to remove leading and/or trailing white-space characters from a string.
Happy coding !!!