結構
Substring
一段字符串。
聲明
@frozen struct Substring
概述
當您創建一個字符串切片時,結果是一個 Substring
實例。對子字符串進行操作既快速又高效,因為子字符串與原始字符串共享其存儲空間。 Substring
類型呈現與 String
相同的接口,因此您可以避免或推遲對字符串內容的任何複製。
以下示例創建一個greeting
字符串,然後查找第一句的子字符串:
let greeting = "Hi there! It's nice to meet you! 👋"
let endOfSentence = greeting.firstIndex(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"
您可以對子字符串執行許多字符串操作。在這裏,我們找到第一個句子的長度並創建一個大寫版本。
print("'\(firstSentence)' is \(firstSentence.count) characters long.")
// Prints "'Hi there!' is 9 characters long."
let shoutingSentence = firstSentence.uppercased()
// shoutingSentence == "HI THERE!"
將子字符串轉換為字符串
這個例子定義了一個帶有一些非結構化數據的rawData
字符串,然後使用該字符串的prefix(while:)
方法來創建一個數字前綴的子字符串:
let rawInput = "126 a.b 22219 zzzzzz"
let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
// numericPrefix is the substring "126"
當您需要存儲子字符串或將其傳遞給需要 String
實例的函數時,您可以使用 String(_:)
初始化程序將其轉換為 String
。調用此初始化程序會將子字符串的內容複製到新字符串。
func parseAndAddOne(_ s: String) -> Int {
return Int(s, radix: 10)! + 1
}
_ = parseAndAddOne(numericPrefix)
// error: cannot convert value...
let incrementedPrefix = parseAndAddOne(String(numericPrefix))
// incrementedPrefix == 127
或者,您可以將采用String
的函數轉換為通過StringProtocol
協議通用的函數。以下代碼聲明了 parseAndAddOne(_:)
函數的通用版本:
func genericParseAndAddOne<S: StringProtocol>(_ s: S) -> Int {
return Int(s, radix: 10)! + 1
}
let genericallyIncremented = genericParseAndAddOne(numericPrefix)
// genericallyIncremented == 127
您可以使用 String
或 Substring
的實例調用此通用函數。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift Substring.UnicodeScalarView insert(contentsOf:at:)用法及代碼示例
- Swift Substring.UTF16View enumerated()用法及代碼示例
- Swift Substring.UTF16View sorted(by:)用法及代碼示例
- Swift Substring.UnicodeScalarView reversed()用法及代碼示例
- Swift Substring.UTF8View split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift Substring.UnicodeScalarView suffix(from:)用法及代碼示例
- Swift Substring last用法及代碼示例
- Swift Substring remove(at:)用法及代碼示例
- Swift Substring.UTF8View reduce(_:_:)用法及代碼示例
- Swift Substring reversed()用法及代碼示例
- Swift Substring.UTF8View sorted()用法及代碼示例
- Swift Substring split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift Substring.UTF16View randomElement()用法及代碼示例
- Swift Substring.UTF8View filter(_:)用法及代碼示例
- Swift Substring.UnicodeScalarView reduce(into:_:)用法及代碼示例
- Swift Substring.UTF16View elementsEqual(_:)用法及代碼示例
- Swift Substring first用法及代碼示例
- Swift Substring.UnicodeScalarView append(_:)用法及代碼示例
- Swift Substring.UTF16View indices用法及代碼示例
- Swift Substring ...(_:_:)用法及代碼示例
- Swift Substring randomElement(using:)用法及代碼示例
- Swift Substring contains(where:)用法及代碼示例
- Swift Substring.UTF8View prefix(through:)用法及代碼示例
- Swift Substring init(repeating:count:)用法及代碼示例
- Swift Substring.UTF8View subscript(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Substring。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。