In this shot, we will learn to check if a string is empty or not.
In Golang, we can do this by:
The code below shows how to check if a string is empty by comparing it with an empty string:
package mainimport ("fmt")func main() {// initialize an empty and a non-empty stringstr1 := ""str2 := "edpresso"if str1 == "" {// will be printed on the console, since str1 is emptyfmt.Println("String 1 is empty")}if str2 == "" {// will be skipped, since str2 is not emptyfmt.Println("String 2 is empty")}}
The code below shows how to check if a string is empty by evaluating the length of the string:
package mainimport ("fmt")func main() {// initialize an empty and a non-empty stringstr1 := ""str2 := "edpresso"if len(str1) == 0 {// will be printed on the console, since str1 is emptyfmt.Println("String 1 is empty")}if len(str2) == 0 {// will be skipped, since str2 is not emptyfmt.Println("String 2 is empty")}}
Note: If a string contains only white spaces, we can use the
TrimSpace()
method to remove them before checking if it’s empty or not.