结构
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。