เช็คว่าสตริงหนึ่งมีสตริงอีกตัวหนึ่งอยู่ภายใน ใช้ contains(_:) หรือ range(of:)
วิธีที่ 1: contains(_:) - เรียบง่ายที่สุด (Swift 2+)
let fullString = "Tutorials Point"
let substring = "Point"
if fullString.contains(substring) {
print("Contains 'Point'")
} else {
print("Does not contain")
}
// Output: Contains 'Point'
วิธีที่ 2: range(of:) - ยืดหยุ่นกว่า
let fullString = "one two three"
let substring = "Point"
if fullString.range(of: substring) != nil {
print("Contains")
} else {
print("Does not contain")
}
// Output: Does not contain
ตัวเลือกเพิ่มเติมของ range(of:)
// Case Insensitive
"Hello World".range(of: "world", options: .caseInsensitive) != nil // true
// Regular Expression
"Hello 123".range(of: "\\d+", options: .regularExpression) != nil // true
// Anchored (ต้น/ท้าย)
"Hello World".range(of: "Hello", options: .anchored) != nil // true
"Hello World".range(of: "World", options: [.anchored, .backwards]) != nil // true
// Locale Aware (สำหรับภาษาไทย, อักษรพิเศษ)
"สวัสดี".range(of: "สวัส", options: [], locale: Locale(identifier: "th")) != nil
Extension Helper
extension String {
func contains(_ string: String, caseSensitive: Bool = true) -> Bool {
let options: NSString.CompareOptions = caseSensitive ? [] : [.caseInsensitive]
return range(of: string, options: options) != nil
}
func containsRegex(_ pattern: String) -> Bool {
return range(of: pattern, options: .regularExpression) != nil
}
}
// ใช้งาน
"Hello World".contains("world") // false
"Hello World".contains("world", caseSensitive: false) // true
"abc123".containsRegex("\\d+") // true
Performance
contains(_:)- เร็วที่สุดสำหรับ Exact Matchrange(of:)- เหมาะสำหรับ Case Insensitive, Regex, Locale- สำหรับการค้นหาบ่อย/ข้อความยาว → ใช้
NSStringหรือ Library (Aho-Corasick)