Để kiểm tra xem một chuỗi có chứa chuỗi con khác trong Swift, có 2 cách phổ biến: contains(_:) và range(of:).
Cách 1: contains(_:) - Đơn giản, trực quan (Swift 2+)
let fullString = "Tutorials Point"
let subString = "Point"
if fullString.contains(subString) {
print("Có chứa '\(subString)'")
} else {
print("Không chứa")
}
Cách 2: range(of:) - Linh hoạt hơn (có options)
let fullString = "one two three"
let subString = "Point"
if fullString.range(of: subString) != nil {
print("Có chứa")
} else {
print("Không chứa")
}
Kết quả test
var str1 = "Tutorials Point"
var str2 = "one two three"
var check = "Point"
str1.contains(check) // true
str2.contains(check) // false
str1.range(of: check) // Range tồn tại
str2.range(of: check) // nil

Ví dụ thêm
let str = "12312$$33@"
str.contains("%%") // false
str.contains("$$") // true
str.range(of: "%%") // nil
str.range(of: "$$") // Range tồn tại

So sánh & Options
| Tiêu chí | contains(_:) | range(of:) |
|---|---|---|
| Cú pháp | Đơn giản | Hơi dài hơn |
| Case insensitive | Không hỗ trợ trực tiếp | Hỗ trợ: .caseInsensitive |
| Regex | Không | Hỗ trợ: .regularExpression |
| Trả về | Bool | Range? (vị trí) |
Ví dụ Case Insensitive
"Hello World".range(of: "world", options: .caseInsensitive) != nil // true
"Hello World".localizedCaseInsensitiveContains("world") // true (iOS 8+)
Khuyến nghị
- Dùng
contains(_:)cho trường hợp đơn giản, case-sensitive. - Dùng
range(of:options:)khi cần case-insensitive, regex, hoặc cần vị trí (Range). - iOS 8+:
localizedCaseInsensitiveContains(_:)cho so sánh không phân biệt chữ hoa/thường theo locale.