Swift 程序遍历字符串的每个字符

swiftserver side programmingprogramming更新于 2025/9/21 6:22:17

在 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() 方法进行迭代。它通常返回一个 pair(m, n) 序列,其中 m 表示索引,n 表示其关联的字符。或者说,使用 enumerated() 方法可以获取字符及其关联的索引值。

语法

for(idx, char) in mStr.enumerated(){
    // 循环体
}

这里 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() 方法可以访问字符的索引。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部