Swift 程式遍歷字串中的每個字元
在 Swift 中,我們可以非常輕鬆地遍歷字串的每個字元。為了進行迭代,Swift 提供了以下方法:
使用 for-in 迴圈
使用 forEach() 函式
使用 enumerated() 函式
方法 1:使用 for-in 迴圈
我們可以使用 for-in 迴圈進行迭代。它遍歷字串的每個字元,然後執行迴圈體中給定的表示式,或者將其顯示在輸出螢幕上。
語法
for x in mstr{
// body
}
這裡 mstr 是字串,x 在每次迭代中儲存來自字串的當前字元。
示例
在以下 Swift 程式中,我們將遍歷字串的每個字元。因此,我們首先建立一個字串,然後使用 for-in 迴圈遍歷每個字元並在輸出螢幕上顯示輸出。
import Foundation
import Glibc
let InputString = "This is Swift Tutorial"
print("Characters in the current string: \(InputString) are:")
for char in InputString {
print(char)
}
輸出
Characters in the current string: This is Swift Tutorial are: T h i s i s S w i f t T u t o r i a l
方法 2:使用 forEach() 方法
我們還可以使用 forEach() 方法進行迭代。它對給定字串的每個字元呼叫指定的閉包並顯示輸出。
語法
mStr.forEach{mBody}
這裡 mStr 是字串,mBody 是一個閉包,它以給定字串中的每個字元作為引數,並根據閉包中存在的表示式返回結果。
示例
在以下 Swift 程式中,我們將遍歷字串的每個字元。因此,我們首先建立一個字串,然後在 forEach() 方法中傳遞一個閉包來遍歷輸入字串的每個字元,然後在輸出螢幕上顯示輸出。
import Foundation
import Glibc
let InputString = "This is Swift 7 Tutorial"
print("Characters in the current string: \(InputString) are:")
InputString.forEach{C in print(C)}
輸出
Characters in the current string: This is Swift 7 Tutorial are: T h i s i s S w i f t 7 T u t o r i a l
方法 3:使用 enumerated() 方法
我們還可以使用 enumerated() 方法進行迭代。它通常返回一系列對 (m, n),其中 m 表示索引,n 表示其關聯的字元。或者我們可以說,使用 enumerated() 方法,您可以獲取字元及其關聯的索引值。
語法
for(idx, char) in mStr.enumerated(){
// Body
}
這裡 mStr 是字串,mBody 是迴圈體。idx 表示索引,char 表示當前字元。
示例
在以下 Swift 程式中,我們將遍歷字串的每個字元。因此,我們首先建立一個字串,然後使用 enumerated() 方法遍歷每個字元及其對應的索引,然後顯示輸出。
import Foundation
import Glibc
let InputString = "Swift Tutorial"
print("Characters in the current string: \(InputString) are:")
for (idx, char) in InputString.enumerated() {
print("Character = \(char) and index = \(idx)")
}
輸出
Characters in the current string: Swift Tutorial are: Character = S and index = 0 Character = w and index = 1 Character = i and index = 2 Character = f and index = 3 Character = t and index = 4 Character = and index = 5 Character = T and index = 6 Character = u and index = 7 Character = t and index = 8 Character = o and index = 9 Character = r and index = 10 Character = i and index = 11 Character = a and index = 12 Character = l and index = 13
結論
這就是我們如何遍歷字串的每個字元。所有三種方法都能有效地工作。每種方法提供不同的功能,例如,for-in 迴圈使用 return、continue、break 等語句可以更好地控制迭代,而使用 forEach() 函式可以利用閉包的優勢,使用 enumerated() 方法可以訪問字元的索引。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP