Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีดึงตัวอักษร 4 ตัวสุดท้ายจาก String ใน Swift

ใช้ suffix(_:) (Swift 4+) หรือ substring (เก่า) เพื่อดึงตัวอักษรท้ายสตริง

วิธีที่ 1: suffix(_:) - แนะนำ (Swift 4+)


let str = "12312$$33@"
let last4 = str.suffix(4)
print(last4) // "33@" (Substring)

// แปลงเป็น String
let last4String = String(str.suffix(4))
print(last4String) // "33@"

วิธีที่ 2: substring (Deprecated)


// Swift 3 style (Deprecated)
let last4 = str.substring(from: str.index(str.endIndex, offsetBy: -4))

Extension ใช้งานง่าย


extension String {
    func last(_ count: Int) -> String {
        guard count > 0 else { return "" }
        return String(suffix(count))
    }
    
    func last(_ count: Int) -> Substring {
        guard count > 0 else { return "" }
        return suffix(count)
    }
}

// ใช้งาน
"Hello World".last(4)  // "orld"
"สวัสดี".last(2)       // "ดี"
"Hi".last(5)           // "Hi" (ไม่พังถ้าสั้นกว่า)

กรณีพิเศษ


// ดึงท้ายหลัง Character เฉพาะ
let email = "user@example.com"
if let atIndex = email.lastIndex(of: "@") {
    let domain = email[email.index(after: atIndex)...] // "example.com"
}

// Split และดึงท้าย
let path = "/users/123/profile"
let lastComponent = path.split(separator: "/").last // "profile"

Performance Note

  • suffix คืนค่า Substring (Shared Memory, O(1))
  • แปลงเป็น String เมื่อต้องเก็บนาน (Copy)
  • ใช้ Substring ใน Scope สั้นๆ เพื่อประหยัด Memory