用Swift列举4种以上字符串遍历的方法,要求给出示例程序
时间: 2024-04-29 10:23:39 浏览: 100
1. for-in循环遍历字符串中的每个字符:
```
let str = "Hello, World!"
for char in str {
print(char)
}
```
2. 使用字符串的`characters`属性遍历每个字符:
```
let str = "Swift"
for char in str.characters {
print(char)
}
```
3. 使用`enumerated()`方法遍历字符串中的索引和字符:
```
let str = "Apple"
for (index, char) in str.enumerated() {
print("Character at index \(index) is \(char)")
}
```
4. 使用`forEach()`方法遍历字符串中的每个字符:
```
let str = "Hello, Swift!"
str.forEach { char in
print(char)
}
```
相关问题
用swift写一个程序,要求如下将字符串变量animals赋值为4种动物(4种动物名用空格隔开)。 遍历输出。 要求从字符串的起始位置和结束位置分别出发检索,实现将animals中的四个动物分别保存在4个字符串中(不要含空格
以下是用Swift实现的程序:
```swift
var animals = "猫 狗 鸟 鱼"
// 遍历输出
for animal in animals.components(separatedBy: " ") {
print(animal)
}
// 从起始位置检索动物名
if let startIndex = animals.startIndex,
let endIndex = animals.firstIndex(of: " ") {
let animal1 = String(animals[startIndex..<endIndex])
print(animal1)
}
// 从结束位置检索动物名
if let startIndex = animals.lastIndex(of: " "),
let endIndex = animals.endIndex {
let animal4 = String(animals[startIndex..<endIndex])
print(animal4)
}
// 从起始位置检索第二个动物名
if let startIndex = animals.index(after: animals.startIndex),
let firstSpaceIndex = animals.firstIndex(of: " "),
let secondSpaceIndex = animals.index(after: firstSpaceIndex),
let endIndex = animals.firstIndex(of: " ", after: secondSpaceIndex) ?? animals.endIndex {
let animal2 = String(animals[secondSpaceIndex..<endIndex])
print(animal2)
}
// 从结束位置检索第三个动物名
if let endIndex = animals.lastIndex(of: " "),
let secondSpaceIndex = animals.lastIndex(of: " ", before: endIndex),
let firstSpaceIndex = animals.lastIndex(of: " ", before: secondSpaceIndex),
let startIndex = animals.index(after: firstSpaceIndex) {
let animal3 = String(animals[startIndex..<secondSpaceIndex])
print(animal3)
}
```
输出结果:
```
猫
狗
鸟
鱼
猫
鱼
狗
鸟
```
阅读全文