Go语言程序:检查字符串是否为空或null
Go语言中的字符串是字符的集合。由于Go语言中的字符串是不可变的,因此一旦创建就不能修改。但是,可以通过连接或添加到现有字符串来创建新的字符串。字符串类型是Go语言中的内置类型,可以像其他任何数据类型一样以多种方式使用。
语法
strings.TrimSpace()
要删除字符串中开头和结尾的空格,请使用strings.TrimSpace()函数。
算法
步骤1 − 创建一个main包并声明fmt(格式化包)包。
步骤2 − 创建一个main函数。
步骤3 − 使用内部函数或用户定义函数来确定字符串是否为空。
步骤4 − 使用fmt.Println()函数执行print语句,其中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,len()函数用于测量字符串的长度。
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()函数。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP