@greyson
Есть несколько способов найти определенный символ в строке в Swift:
- Используя метод contains:
1
2
3
4
|
let text = "Hello, world!"
if text.contains("o") {
print("Found 'o' in text")
}
|
- Используя метод contains(where:):
1
2
3
4
|
let text = "Hello, world!"
if text.contains(where: { $0 == "o" }) {
print("Found 'o' in text")
}
|
- Используя метод firstIndex(of:):
1
2
3
4
|
let text = "Hello, world!"
if let index = text.firstIndex(of: "o") {
print("Found 'o' at index (index)")
}
|
- Используя свойство contains у массива символов из строки:
1
2
3
4
|
let text = "Hello, world!"
if text.characters.contains("o") {
print("Found 'o' in text")
}
|
- Используя регулярные выражения:
1
2
3
4
5
6
7
8
|
import Foundation
let text = "Hello, world!"
let regex = try! NSRegularExpression(pattern: "o", options: [])
let range = NSRange(location: 0, length: text.utf16.count)
if let _ = regex.firstMatch(in: text, options: [], range: range) {
print("Found 'o' in text")
}
|