Swift程式:移除陣列中所有指定元素
在這篇文章中,我們將學習如何編寫一個Swift程式來移除陣列中所有指定元素的出現。我們將使用以下方法:
使用內建函式
不使用內建函式
方法一:使用removeAll()函式
為了移除陣列中所有指定元素的出現,我們使用一個預定義的函式`removeAll(where:)`。此函式移除給定序列中滿足給定條件的所有元素。例如:
Array = [2, 3, 5, 67, 2, 87, 2, 68] Element = 2 Output array = [3, 5, 67, 87, 68]
這裡我們將移除原始陣列中所有出現的數字2,並在輸出中顯示陣列中剩餘的元素。
語法
以下是語法:
mutating func removeAll(where removeElement:(self.Element) throws ->Bool)rethrows
這裡`removeElement`是一個閉包,它接收給定序列中的一個元素作為引數,並返回一個布林值,表示是否從給定序列中移除該元素。
演算法
**步驟1** — 建立一個數組。
**步驟2** — 使用`removeAll(where:)`方法移除所有指定元素的出現。
Array.removeAll{$0 == 6}
**步驟3** — 列印輸出
示例
import Foundation
import Glibc
// Creating an array of integer type
var Array : [Int] = [34, 6, 7, 81, 6, 56, 6, 32, 6, 6]
print("Original array:", Array)
// Deleting all the occurrences of 6 in the given array
// Using removeAll(where:) method
Array.removeAll{$0 == 6}
print("Modified array", Array)
輸出
在下面的示例中,我們使用`removeAll(where:)`方法從陣列中移除所有給定數字的出現。
Original array: [34, 6, 7, 81, 6, 56, 6, 32, 6, 6] Modified array [34, 7, 81, 56, 32]
在上面的程式碼中,我們建立了一個整數型別的陣列,其值為:[34, 6, 7, 81, 6, 56, 6, 32, 6, 6]。其中數字6在陣列中出現了5次,現在我們想從陣列中移除所有5次出現的6。因此,我們使用`removeAll{$0 == 6}`,這裡`$0`表示傳遞到閉包中的陣列的第一個元素。`removeAll{$0 == 6}`方法檢查陣列中從索引0到結尾的每個元素,並只移除滿足給定條件的元素。
方法二:不使用內建函式
為了移除陣列中所有指定元素的出現,我們使用條件語句。這裡的條件語句將每個元素與要從陣列中刪除的元素進行比較。如果條件為真,則跳過該元素並列印其餘的陣列元素。
演算法
**步驟1** — 建立一個函式。
**步驟2** — 使用`count`屬性查詢陣列的大小。
**步驟3** — 使用for迴圈遍歷陣列的每個元素。迭代從0到陣列大小-1。
**步驟4** — 使用if-else語句檢查給定的陣列元素是否等於該數字。如果當前陣列元素等於給定的數字,則繼續迴圈,否則列印陣列。
**步驟5** — 在函式外部建立一個數組。
**步驟6** — 將要刪除的數字賦值給一個變數。
**步驟7** — 呼叫函式並將陣列和數字(要刪除的數字)作為引數傳遞。
**步驟8** — 列印輸出。
示例
在下面的示例中,我們使用條件語句從陣列中移除所有給定數字的出現。
import Foundation import Glibc // Creating a function to delete all the // occurrence of 1 from the given array func DeleteElement(arr:[Int], num: Int) { let arrSize = arr.count print("Modified Array:") // Iterate through each element of the array for x in 0..<arrSize { // If the array element is equal to the given num // then continue the loop otherwise print the array if (arr[x] == num) { continue } else { print(arr[x], terminator:",") } } } // Creating an array of integer type var Array : [Int] = [24, 1, 7, 91, 1, 56, 1, 42, 1, 0] print("Original array:", Array) let element = 1 // Calling the function DeleteElement(arr:Array, num: element)
輸出
Original array: [24, 1, 7, 91, 1, 56, 1, 42, 1, 0] Modified Array: 24,7,91,56,42,0,
在上面的程式碼中,我們建立了一個名為`DeleteElement()`的函式,它接收兩個引數:一個數組和一個數字`num`(我們想要移除其所有出現的數字)。在這個函式中,我們遍歷每個陣列元素並使用`==`運算子與`num`進行比較。如果條件為真,則繼續迴圈。否則,它將列印其餘的陣列。
結論
因此,為了從陣列中移除所有指定元素的出現,我們可以根據需要使用內建函式或條件語句。兩種方法都能很好地完成任務。