Swift 字符串索引访问和修改字符串

2021-07-28  本文已影响0人  _发强

字符串索引

注意,在 Swift 中,字符串的下标并不是 Int 类型,所以不能用 1234 这样的下标来进行获取。
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)

image.png

字符串截取

这里有一个 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)  

字符串比较

let helloWorld = "Hello,World!"
// 前缀比较
helloWorld.hasPrefix("Hello")

//后缀比较
helloWorld.hasSuffix("World")

上一篇 下一篇

猜你喜欢

热点阅读