Swift 程式移除字串中所有空格


空格字元是一種不可列印字元,表示字串中的空格。為了移除字串中的所有空格,Swift 提供了以下方法:

  • 使用 isWhitespace 屬性

  • 使用 component() 函式

  • 使用 replacingOccurrences(of:with:) 方法

  • 使用正則表示式

方法 1:使用 isWhitespace 屬性

isWhitespace 屬性用於檢查給定字元是否為空格字元。在這種方法中,我們使用 isWhitespace 屬性和 filter() 方法來移除給定字串中存在的所有空格。

語法

var res = str.filter{!$0.isWhitespace}

這裡,filter() 方法被呼叫到 str 字串上。傳遞給函式的閉包(!$0.isWhitespace) 檢查字串中的每個字元,如果字元不是空格字元,則返回 true。

示例

在以下 Swift 程式中,我們將從字串中移除所有空格。為此,我們建立一個函式,該函式以字串作為輸入。然後,該函式使用 filter() 方法和 !$0.isWhitespace 閉包對輸入的字串進行檢查,逐個字元判斷它們是否為空格字元。如果是,則刪除該字元並將非空格字元儲存到變數中。移除所有空格後,使用 String() 初始化器將剩餘的字元轉換回字串,並返回最終不包含任何空格的字串。

import Foundation
import Glibc

func removeWhitespacesFromString(mStr: String) -> String {

    let filteredChar = mStr.filter { !$0.isWhitespace }
    return String(filteredChar)
}

let input = "Mohan learn swift   programming"
let resStr = removeWhitespacesFromString(mStr: input)

print("Original String:", input)
print("String without whitespaces:", resStr)

輸出

Original String: Mohan learn swift   programming
String without whitespaces: Mohanlearnswiftprogramming

方法 2:使用 components() 方法

components() 方法用於從給定字串建立子字串陣列,其中每個子字串由指定的分割符分隔。因此,這裡我們使用 components(separatedBy:.whitespaces) 方法,並使用 .wihitespaces 作為引數來建立子字串陣列,其中子字串由空格字元分隔。之後,我們使用 joined() 函式將所有子字串連線成一個不包含任何空格的字串。

語法

str.components(separatedBy:.whitespaces)

這裡,component() 方法被呼叫到 str 字串上,並返回一個由空格分隔的子字串陣列。

示例

在以下 Swift 程式中,我們將從字串中移除所有空格。為此,我們建立一個函式,該函式以字串作為輸入。然後,該函式使用 components(separatedBy: .whitespaces) 方法將輸入字串轉換為基於空格的子字串陣列。然後,它使用 joined() 方法將所有子字串連線成一個不包含空格的字串。

import Foundation
import Glibc

func removeWhitespacesFromString(mStr: String) -> String {

   let chr = mStr.components(separatedBy: .whitespaces)
   let resString = chr.joined()
   return resString
}

let input = "Today is the  rainy day"
let resStr = removeWhitespacesFromString(mStr: input)

print("Original String:", input)
print("String without whitespaces:", resStr)

輸出

Original String: Today is the  rainy day
String without whitespaces: Todayistherainyday

方法 3:使用 replacingOccurrences() 方法

replacingOccurrences() 方法用於將指定字元的所有出現替換為給定字元。因此,這裡我們用空字串 (“”) 替換空格字元 (“ ”) 的所有出現,以從字串中移除所有空格。

語法

func replacingOccurrences{of: tchar, with: rchar}

這裡,此函式接受兩個引數,一個是 tchar,它是我們要替換的字元;另一個是 rchar,它是替換 tchar 的替換字元。

示例

在以下 Swift 程式中,我們將從字串中移除所有空格。為此,我們建立一個字串,然後使用 replacingOccurrences(of:with:) 方法並將空格 (“ ”) 替換為空字串 (“”),並返回一個不包含空格的新字串。最後,我們將顯示輸出。

import Foundation
import Glibc

let input = "Siya  run a beautiful  car"

let resultantString = input.replacingOccurrences(of: " ", with: "")
print("Original string:", input)
print("String without whitespaces:", resultantString)

輸出

Original string: Siya  run a beautiful  car
String without whitespaces: Siyarunabeautifulcar

方法 4:使用正則表示式

我們還可以使用正則表示式從字串中移除所有空格。這裡我們使用 NSRegularExpression 類的 stringByReplacingMatches() 函式來移除所有空格。

示例

在以下 Swift 程式中,我們將從字串中移除所有空格。為此,我們建立一個字串,然後使用 “\s” 模式建立一個 NSRegularExpression 類的例項。其中 “\s” 模式用於匹配空格字元。然後,我們使用 stringByReplacingMatches() 函式將所有空格的出現替換為空字串。最後,我們得到一個不包含空格的字串。

import Foundation
import Glibc

let input = "Siya  run a beautiful  car"

let regexValue = try! NSRegularExpression(pattern: "\\s", options: [])
let newString = regexValue.stringByReplacingMatches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count), withTemplate: "")

print("Original String:", input)
print("String without whitespaces:", newString)

輸出

Original String: Siya  run a beautiful  car
String without whitespaces: Siyarunabeautifulcar

結論

這就是我們如何從字串中移除所有空格的方法。您可以使用上述任何方法從字串中移除所有空格。所有方法都能很好地完成其工作。從字串中移除空格在資料驗證、格式化、比較和搜尋、解析等方面很有用。

更新於: 2023年6月14日

6K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告