Swift 程式檢查給定字串是否為空


要檢查給定的字串是否為空,Swift 提供了一個名為 isEmpty 的內建屬性。如果給定的字串為空,則此屬性將返回 true。如果給定的字串不為空,則返回 false。這裡空字串是指長度為 0 的字串,或者我們可以說一個不包含任何字元的字串。

String 1 = “Swift”
String 2 = “”

其中字串 1 不是空字串,因為它包含一系列字元或具有一定的長度。而字串 2 是一個空字串,因為它不包含任何內容或長度為 0。

語法

Str.isEmpty

其中 Str 是要檢查其是否為空的字串,使用 isEmpty 屬性。

演算法

  • 步驟 1 − 建立一個字串。

  • 步驟 2 − 使用 isEmpty 屬性檢查給定字串是否為空。

  • 步驟 3 − 如果給定的字串為空,則列印“字串為空”。

  • 步驟 4 − 如果給定的字串不為空,則列印“字串不為空”。

示例 1

在以下 Swift 程式中,我們檢查給定的字串是否為空。因此,我們將建立一個字串,然後我們將使用 isEmpty 屬性來檢查當前字串是否為空。如果 isEmpty 屬性返回 true,則表示當前字串為空。否則不是。

import Foundation
import Glibc

let firstString = "Welcome to TutorialsPoint"

if firstString.isEmpty {
   print("The string is empty")
} else {
   print("The string is not empty")
}

輸出

The string is not empty

示例 2

眾所周知,空字串的長度為零。因此,我們還可以使用 count 屬性檢查給定的字串是否為空。count 屬性返回字串的大小。因此,如果字串的大小為 0,則表示字串為空。否則不是。

import Foundation
import Glibc

let mString = ""

if mString.count == 0 {
   print("The string is empty")
} else {
   print("The string is not empty")
}

輸出

The string is empty

結論

因此,這就是我們如何檢查給定的字串是否為空。isEmpty 和 count 方法都將返回相同的返回值。但是,檢查字串是否為空的最合適方法是 isEmpty 方法。

更新於: 2023年5月9日

2K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.