您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Swift 學習筆記 Day 14:字串的插入、刪除與替換

編輯:iOS 開發綜合

在 Swift 中,字串支援多種插入、刪除與替換操作。本文整理早期 Swift 版本中常見的幾個方法,並透過範例說明各自的用途。

常用方法

  • splice(_:atIndex:):在指定索引位置插入字串。
  • insert(_:atIndex:):在指定索引位置插入單一字元。
  • removeAtIndex(_:):刪除指定索引位置的字元。
  • removeRange(_:):刪除指定範圍內的字串。
  • replaceRange(_:with:):以字串或字元替換指定範圍。

程式碼範例

var str = "Swift"
print("原始字串:\(str)")

str.splice("Objective-C and ".characters, atIndex: str.startIndex)
print("插入字串後:\(str)")

str.insert(".", atIndex: str.endIndex)
print("插入 . 字元後:\(str)")

str.removeAtIndex(str.endIndex.predecessor())
print("刪除 . 字元後:\(str)")

var startIndex = str.startIndex
var endIndex = advance(startIndex, 9)
var range = startIndex...endIndex
str.removeRange(range)
print("刪除範圍後:\(str)")

startIndex = str.startIndex
endIndex = advance(startIndex, 0)
range = startIndex...endIndex
str.replaceRange(range, with: "C++")
print("替換範圍後:\(str)")

執行結果

原始字串:Swift

插入字串後:Objective-C and Swift

插入 . 字元後:Objective-Cand Swift.

刪除 . 字元後:Objective-Cand Swift

刪除範圍後:C and Swift

替換範圍後:C++ and Swift

需要注意的是,不同 Swift 版本的字串 API 可能有所調整,例如後續版本更常使用 insert(contentsOf:at:) 等方法。初學時可以先理解索引、範圍與替換的概念,再對照自身使用的 Swift 版本查閱對應 API。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved