Solved: How to test if string is empty in GoLang?


GOLANG Solutions, GO

Reviewer: Deepak Prasad

In this article, we will discuss How to test if string is empty or not empty in golang? Golang is a relatively new language based on the C language but with better memory and garbage management.

Here we will discuss 3 different ways of how to test if a string is empty  in golang.

Why we need TrimSpace() when working with strings in GO?

TrimSpace() is a method that trims out the \t,\f,\n,\v,\r of a string to check how to test if a string is empty in golang , if this function is not used, string nullity is failed, and if the string has any of the above special characters , the string must be empty, but it does not return empty because the space is also considered to be a character

Check string is empty without TrimSpace()

Here I have written a small go code to read some input from user and check if the received input is empty or not.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter text: ")
	text, _ := reader.ReadString('\n')
	fmt.Println(text)

	if text == "" {
		fmt.Println("Match")
	} else {
		fmt.Println("No-Match")
	}

}

We run this code and just hit Enter w

# go run main.go 
Enter text:

No-Match

As you can see, even though I gave an empty input, the string was not considered as empty.

Check string is empty with TrimSpace()

Here I have updated the same code to use TrimSpace() on the string received as input:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter text: ")
	text, _ := reader.ReadString('\n')
	fmt.Println(text)

	if strings.TrimSpace(text) == "" {
		fmt.Println("Match")
	} else {
		fmt.Println("No-Match")
	}

}

Now if you notice, the empty input is detected and considered as empty string in our if condition. This is because we have removed the new line character using TrimSpace()

# go run main.go 
Enter text:


Match

Method-1: Compare String with null

In the piece of code written below, we will use the TrimSpace() function, this function is a golang function is used to trim out the spaces in a string.

Here,

  1. Take a string input from the user.
  2. Trim the Spaces of the string.
  3. After trimming the spaces, check if the string is null or not.
  4. If the string is null, it's empty.
  5. If not, the string is not empty.

Sample Code:

// Code to test if string is empty in golang
package main

// imports
import (
	"fmt"
	"strings"
)

// check if string is empty or not in golang
func main() {
	// initialise string
	var str string
	// take input string
	fmt.Printf("Enter a string: ")
	// scan input string
	fmt.Scanln(&str)
	// trim space and check if string is empty or not in golang
	if strings.TrimSpace(str) == "" {
		// if string is empty
		fmt.Println("String is empty")
	} else {
		// if not empty
		fmt.Println("String is not empty")
	}
}

Let's execute this code:

]# go run main.go 
Enter a string: hello
String is not empty


]# go run main.go 
Enter a string: 
String is empty

So, our go code is successfully able to test if string is empty or not.

Method-2: Use length property to check if string is empty

In this piece of code below, we will check how to test if string is empty in golang by comparing the length of the string.  If the length of the string is 0 then it is empty and vice versa

This method and the method above use the trim space method but in the example above, the space is trimmed and checked with a null array, while in this method the array is trimmed, and then its length is compared, whether it is empty or not.

// Code to test if string is emtpy in golang?
package main

// imports
import (
	"fmt"
	"strings"
)

// check if string is empty or not
func main() {
	// initialise string
	var str string
	//take input string
	fmt.Printf("Enter a string: ")
	// scan input string
	fmt.Scanln(&str)
	strings.TrimSpace(str)
	// str.length ==0 then it is empty string
	if len(str) == 0 {
		// if string is empty
		fmt.Println("String is empty")
	} else {
		// if not empty
		fmt.Println("String is not empty")
	}
}

Execute the code above:

In case string is empty :

]# go run main.go 
Enter a string: 
String is empty

In case the string is not empty :

]# go run main.go 
Enter a string: hello
String is not empty

Method-3: Create Boolean Function to check multiple strings

This method is very similar to the ones we did above, the only difference is that a function will be created which will be of the type boolean, the function will compare the string passed to it as a parameter with a null string , if both strings are equal the function will return true, which indicates the string is empty and vice versa.

// Code to test if string is empty in golang
package main

// imports
import (
	"fmt"
	"strings"
)

func checkEmpty(s string) bool {
	if strings.TrimSpace(s) == "" {
		return true
	} else {
		return false
	}
}

// check if string is empty or not
func main() {
	// initialise string
	var str string
	// take input string
	fmt.Printf("Enter a string: ")
	// scan input string
	fmt.Scanln(&str)
	strings.TrimSpace(str)
	// use check string
	if checkEmpty(str) {
		// if string is empty
		fmt.Println("String is empty")
	} else {
		// if not empty
		fmt.Println("String is not empty")
	}
}

In case of empty string

]# go run main.go 
Enter a string: 
String is empty

In the case of a non-empty string

]# go run main.go 
Enter a string: hello
String is not empty

Conclusion

In this article we have seen how to test if string is empty in golang? using different methods , first method we studied was comparing the string with a null string, if both were equal the string must be empty, the second method was comparing the length of string with 0, in case it were 0 the string was empty, and the third way was to check it using a boolean function.

For unusual cases How to test if string is empty in golang ?  like if space was entered, the string must still be empty since space is not counted as a non-empty string, we used the TrimSpace function of the strings library, which trimmed off any spaces entered by the user as an input and then check the string for empty conditions.

Further Reading

Strings in golang
Strings TrimSpace()

Azka Iftikhar

Azka Iftikhar

She is proficient in multiple programming languages, including C++, GO, and Java, she brings a versatile skillset to tackle a wide array of challenges. Experienced Computer Scientist and Web Developer, she excels as a MERN Stack Expert. You can check her professional profile on GitHub which captures her experience and portfolio.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

1 thought on “Solved: How to test if string is empty in GoLang?”

Leave a Comment