Как найти определенный символ в string в swift?

Пользователь

от greyson , в категории: Swift , год назад

Как найти определенный символ в string в swift?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

1 ответ

Пользователь

от rachel , год назад

@greyson 

Есть несколько способов найти определенный символ в строке в Swift:

  1. Используя метод contains:
1
2
3
4
let text = "Hello, world!"
if text.contains("o") {
    print("Found 'o' in text")
}


  1. Используя метод contains(where:):
1
2
3
4
let text = "Hello, world!"
if text.contains(where: { $0 == "o" }) {
    print("Found 'o' in text")
}


  1. Используя метод firstIndex(of:):
1
2
3
4
let text = "Hello, world!"
if let index = text.firstIndex(of: "o") {
    print("Found 'o' at index (index)")
}


  1. Используя свойство contains у массива символов из строки:
1
2
3
4
let text = "Hello, world!"
if text.characters.contains("o") {
    print("Found 'o' in text")
}


  1. Используя регулярные выражения:
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")
}