字符串索引
注意,在 Swift 中,字符串的下标并不是 Int 类型,所以不能用 1234 这样的下标来进行获取。
- 使用 index(before:) 和 index(after:) 方法来访问给定索引的前后
- 要访问给定索引更远的索引, 可以使用 index(_:offsetBy:)
- 使用 indices 属性来访问字符串中每个字符的索引
let str = "Guten Tag!"
str[str.startIndex]
str[str.index(after: str.startIndex)]
// 这里要注意,str[str.endIndex] 是已经越界了,
// 要获取最后一个字符串,通过下面方法
str[str.index(before: str.endIndex)]
let index = str.index(str.startIndex, offsetBy: 7) // 从第一个开始但不包括,往后数第7位
str[index]

插入字符串
var hello = "hello"
// 插入单个字符
hello.insert("!", at: hello.endIndex)
// 插入字符串
hello.insert(contentsOf: " World", at: hello.index(before: hello.endIndex))

删除字符串
引用上文中的字符串
// 删除单个字符串
hello.remove(at: hello.index(before: hello.endIndex))
hello
// 删除字符区间
let range = hello.index(hello.endIndex, offsetBy: -6)..<hello.endIndex
hello.removeSubrange(range)

字符串截取
这里有一个 SubString(子字符串) 的类型概念,
SubString,拥有大部分String 的属性.
SubString 会重用 String 的一部分内存, 比较省内存
也就是说, SubString 并没有重新创建一个对象, 而是把指针指向了 String 内存中,当前内容所在的位置。
示例:
逗号分隔,然后分别获取前后内容。
let helloWorld = "Hello,World!"
// 先获取 逗号的下标。 ?? 表示如果前面的表达式为 nil 则返回后面的结果。
let i = helloWorld.firstIndex(of: ",") ?? helloWorld.endIndex
// 获取"," 之前的内容, ..< 是区间运算符,(..<3 表示获取 3之前的区间,不包括3)
let beginning = helloWorld[..<i] // beginning 在这里就属于 SubString 类型。
// 获取","之后的区间, 注意,这里只是获取到了区间,
let endRange = helloWorld.index(after: i)..<helloWorld.endIndex
let end = helloWorld[endRange] // end 也是属于 SubString 类型,
//这里就直接用初始化器语法 转换成了 String 类型。
String(beginning) // 属于String 类型 ,
String(end)
字符串比较
- == 和 !=
- 前缀比较(hasPrefix)
- 后缀比较(hasSuffix)
let helloWorld = "Hello,World!"
// 前缀比较
helloWorld.hasPrefix("Hello")
//后缀比较
helloWorld.hasSuffix("World")
网友评论