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()函式。
廣告