以下所有示例均使用
var str = "Hello, playground"
Swift 4
字符串在 Swift 4 中进行了相当大的修改。现在当你从字符串中获取一些子字符串时,你会得到一个Substring
输入 back 而不是 aString
。为什么是这样?字符串是 Swift 中的值类型。这意味着如果您使用一个字符串来创建一个新字符串,则必须将其复制过来。这有利于稳定性(没有人会在您不知情的情况下更改它),但对效率不利。
另一方面,子字符串是对其来源的原始字符串的引用。这是来自文档 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html说明了这一点。
无需复制,因此使用效率更高。但是,想象一下您从一百万个字符的字符串中得到了十个字符的子字符串。因为子字符串引用字符串,所以只要子字符串存在,系统就必须保留整个字符串。因此,每当您完成对子字符串的操作时,请将其转换为字符串。
let myString = String(mySubstring)
这将仅复制子字符串,并且保存旧字符串的内存可以是回收的 https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html。子字符串(作为一种类型)的寿命是短暂的。
Swift 4 的另一个重大改进是字符串(再次)是集合。这意味着无论你能对 Collection 做什么,你都可以对 String 做(使用下标、迭代字符、过滤等)。
以下示例展示了如何在 Swift 中获取子字符串。
获取子串
您可以使用下标或许多其他方法(例如,prefix
, suffix
, split
)。你还需要使用String.Index
而不是一个Int
不过,该范围的索引。 (看我的另一个答案 https://stackoverflow.com/a/39676940/3681880如果您需要帮助。)
字符串的开头
您可以使用下标(注意 Swift 4 的单边范围):
let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str[..<index] // Hello
or prefix
:
let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str.prefix(upTo: index) // Hello
甚至更简单:
let mySubstring = str.prefix(5) // Hello
字符串结尾
使用下标:
let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str[index...] // playground
or suffix
:
let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str.suffix(from: index) // playground
甚至更简单:
let mySubstring = str.suffix(10) // playground
请注意,当使用suffix(from: index)
我必须使用从末尾倒数-10
。仅仅使用时没有必要suffix(x)
,只需要最后一个x
字符串的字符。
字符串中的范围
我们在这里再次简单地使用下标。
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
let mySubstring = str[range] // play
转换Substring
to String
不要忘记,当您准备好保存子字符串时,应该将其转换为String
这样旧字符串的内存就可以被清理掉。
let myString = String(mySubstring)
使用Int
索引扩展?
我很犹豫是否要使用Int
阅读文章后基于索引扩展Swift 3 中的字符串 https://oleb.net/blog/2016/08/swift-3-strings/作者:Airspeed Velocity 和 Ole Begemann。虽然在 Swift 4 中,字符串是集合,但 Swift 团队故意不使用Int
索引。它还是String.Index
。这与 Swift 字符由不同数量的 Unicode 代码点组成有关。必须为每个字符串唯一计算实际索引。
不得不说,希望Swift团队能找到一种抽象的方法String.Index
将来。但在那之前,我选择使用他们的 API。它帮助我记住字符串操作不仅仅是简单的Int
索引查找。