Golang program to check if a string is empty or null


String in Golang is a collection of characters. Since strings in Go are immutable, they cannot be modified after they have been produced. Concatenating or adding to an existing string, however, enables the creation of new strings. A built-in type in Go, the string type can be used in a variety of ways much like any other data type.

Syntax

strings.TrimSpace()

To eliminate leading and trailing white space from a string, use the strings.TrimSpace() function.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package.

  • Step 2 − Create a main function.

  • Step 3 − Using internal function or user-defined function determine whether the string is empty or not.

  • Step 4 − The print statement is executed using fmt.Println() function where ln means new line.

Example 1

In this example, we will see how to consider a string as empty or null with the help of if-else statement

package main
import (
    "fmt"
)

//create main function to execute the program
func main() {
   var value string       //declare a string variable

   if value == "" {
        fmt.Println("The input string is empty") 
   } 
   if value == "" || value == "null" {
      fmt.Println("The input string is null") //if it satisfies the if statement print the string is null
   }
}

Output

The input string is empty
The input string is null

Example 2

In this example we will learn how to check if a string is empty or null with the help of TrimSpace function which is a built-in function. The output will be printed on the console.

package main
import (
	"fmt"
	"strings"  //import necessary packages fmt and strings 
)

//create main function to execute the program
func main() {
	var input string    //declare a string variable

	// Check if the string is empty
	if len(strings.TrimSpace(input)) == 0 {
		fmt.Println("The input string is empty or null")  //if condition satisfies print the string is empty or null
	}
}

Output

The input string is empty or null

Example 3

In this example we will learn how to to check is string is empty or null with the help of len() function which measures the length of string

package main
import "fmt"

func main() {
	var mystr string  //initialize a string

	if len(mystr) == 0 {
		fmt.Println("String is empty") //if the length of string is 0 print its empty
	} else {
		fmt.Println("String is not empty") //else print not empty
	}
}

Output

String is empty

Conclusion

We executed the program of checking if a string is empty or null using three examples. In the first example we used if-else conditional statement, in the second example we used TrimSpace built-in function along with the if-else condition and in the third example we used the len() function.

Updated on: 01-Feb-2023

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements