Golang 用于检查字符串是否为空或null
Golang中的字符串是字符的集合。由于Go中的字符串是不可变的,所以在生成后不能修改。但是,可以通过连接或添加到现有字符串来创建新字符串。作为Go中的内置类型,字符串类型可以像其他任何数据类型一样以多种方式使用。
语法
strings.TrimSpace()
为了从字符串中删除开头和结尾的空格,使用strings.TrimSpace()函数。
步骤
- 步骤1 - 创建一个main包,并声明fmt(format包)包。
-
步骤2 - 创建一个main函数。
-
步骤3 - 使用内部函数或用户定义的函数确定字符串是否为空。
-
步骤4 - 使用fmt.Println()函数执行打印语句,其中ln表示新行。
示例1
在此示例中,我们将看到如何使用if-else语句将字符串视为空或null。
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
}
}
输出
The input string is empty
The input string is null
示例2
在这个示例中,我们将学习如何使用TrimSpace函数来检查一个字符串是否为空或null。输出将打印在控制台上。
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
}
}
输出
The input string is empty or null
示例3
在本例中,我们将学习如何使用len()函数检查字符串是否为空或null,该函数可以测量字符串的长度。
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
}
}
输出
String is empty
结论
我们通过三个示例执行了检查字符串是否为空或null的程序。在第一个示例中,我们使用了if-else条件语句,在第二个示例中,我们使用了TrimSpace内置函数以及if-else条件,并且在第三个示例中,我们使用了len()函数。