“`html
字串擷取
在 Swift 中,字串擷取是非常常用的操作。透過以下方法,你可以方便地擷取字串的特定部分,這些方法將會使用到 Swift 5.7 的最新語法。
使用 index 和 offsetBy 進行字串擷取
你可以利用 index(_:offsetBy:)
方法來獲得字串的特定位置,並根據這些位置擷取字串的前綴或後綴。
let cutString = "hello world"
let helloIndex = cutString.index(cutString.startIndex, offsetBy: 5)
print(String(cutString.suffix(from: helloIndex)))
// 輸出: " world"
print(String(cutString.prefix(upTo: helloIndex)))
// 輸出: "hello"
// 從後面數來 第-5個
let worldIndex = cutString.index(cutString.endIndex, offsetBy: -5)
print(String(cutString.suffix(from: worldIndex)))
// 輸出: "world"
print(String(cutString.prefix(upTo: worldIndex)))
// 輸出: "hello "
使用 index(before:) 取得之前的字串部分
// 在 index 之前
print(String(cutString.suffix(from: cutString.index(before: cutString.endIndex))))
// 輸出: "ello world"
print(String(cutString.prefix(upTo: cutString.index(before: cutString.endIndex))))
// 輸出: "h"
使用 index(after:) 取得之後的字串部分
// 在 index 之後
print(String(cutString.suffix(from: cutString.index(after: cutString.startIndex))))
// 輸出: "ello world"
print(String(cutString.prefix(upTo: cutString.index(after: cutString.startIndex))))
// 輸出: "h"
直接使用 index 類型來擷取字串
print(String(cutString.prefix(5)))
// 輸出: "hello"
print(String(cutString[..
取範圍字串:擷取第2~3個字
你也可以使用 NSRange
來擷取指定範圍的字串。以下是一個範例:
let cutBugString = "hello world"
print((cutBugString as NSString).substring(with: NSMakeRange(2, 3)))
// 輸出: "llo"
常見問題與解答(Q&A)
1. 如何在 Swift 中檢查字串是否包含特定字串?
你可以使用 contains
方法來檢查字串是否包含另一個字串。例如:
let text = "hello world"
let containsHello = text.contains("hello") // 返回 true
2. Swift 中的字串是值類型還是引用類型?
在 Swift 中,字串是值類型,這意味著當你將字串賦值給另一個變數時,會創建一個獨立的副本。
3. 如何快速反轉一個字串?
你可以使用 reversed()
方法來反轉字串,並利用 String
的初始化方法轉換回字串。例如:
let originalString = "hello"
let reversedString = String(originalString.reversed()) // "olleh"
Swift更多文章
[教學] Swift 找字串 文字找字串
Swift字串拼接 文字拼接
Swift 字串擷取 文字擷取
Swift - 陣列轉字串 | Array to String | List to String | description
Swift Date 現在星期幾 這個月有幾天
Swift - 正規表達式 (電話/身分證/email)
```
---