swift 4.2 官方文档学习笔记(三)- 字符串和字符

Sellen Wei
5 min readDec 12, 2018

--

这一章来说一下:字符串和字符,对于新手工程师来说,被面的最多的应该就是语言中合并,删除字符等等操作的时间复杂度了吧,但其实这一章有很多有趣的实现方法,掌握了可以使app的开发变得更加灵活。

1. 如果倒入foundation库,就可以在String中访问所有NSString的方法

2. 多行字符串,用三个双引号来包含需要多行表达的字符串,这个以前在modal popup中由于我不会实现,以为要用abstractString后来强制让product engineer把这个给改了,其实实现起来也并不是很难啊,对不起当时的product team了:

let quotation = “””

The White Rabbit put on his spectacles. “Where shall I begin,

please your Majesty?” he asked.

“Begin at the beginning,” the King said gravely,”and go on

till you come to the end; then stop.

“””” //结束双引号前如果有空格,那么所有包含的行前都会有缩进,相反,如果不是跟三个引号对齐,那么空格则会被忽略

3. 初始化空的字符串 var string1 = “” 那么string1.isEmpty = true

4.可以通过for循环来遍历string中的每一个character

5.通过 let exclamationMark: Character = “!” 来声明一个字符

6.[Character] 也可以构造一个string,如下:

let catCharacters: [Character] = [“C”, “a”, “t”, “!”, “?”]

let catString = String(catCharacters)

7. + 和 += 都可以作为合并两个string的运算符号

8.用append来连接character和string

9.转义的特殊字符\ 0(空字符),\\(反斜杠),\ t(水平制表符),\ n(换行符),\ r \ (回车符),\“(双引号)和\’(单个)引号

10. unicode 的表示方法和双引号在string中的表示方法

let wiseWords=”\”Imagination is more important than knowledge\” — Einstein”

// “Imagination is more important than knowledge” — Einstein

let dollarSign=”\u{24}”// $, Unicode scalar U+0024

11. Extended Grapheme Cluster: 这个是一个character集群的概念,简单来说就是可以将两个unicode组成一个character,文档中给出的是韩文的例子,因为韩文是多个字符排列而成的一个字

12.count:计算string长度的

13. index 这里讲了一些如何使用index来查找string中第几位的character,

let greeting = “Guten Tag!”

greeting[greeting.startIndex]

// G

greeting[greeting.index(before: greeting.endIndex)]

// !

greeting[greeting.index(after: greeting.startIndex)]

// u

let index = greeting.index(greeting.startIndex, offsetBy: 7)

greeting[index]

// a

另外还可以通过indices来访问所有index

for index in greeting.indices {

print(“\(greeting[index]) “, terminator: “”)

}

// Prints “G u t e n T a g ! “

14. 在某个位置插入char或者string:

使用.insert(“!”, at: index位置) 来插入字符

使用.insert(contentsOf: “something”, at: index位置) 来插入字符串

15. 在某个位置删除字符或字符串:

使用.remove(at:) 来删除字符

使用.removeSubrange(range) 来移除字符串

需要注意的是以上这些index相关方法,也适用于所有 Array, Dictionary, and Set.

16. substring的内存问题: 由于performance optimization,substring和string共享内存的使用而不占用额外的内存,这点的好处的就是节省空间,缺点就是 “the entire original string must be kept in memory as long as any of its substrings are being used.” 这点就有点像strong指针,在有任何一个指向这个地址的指针仍然被使用的时候,内存就不能被释放。这也算一个trade off,既节省了空间又没有节省空间

17. 前缀后缀:string.hasPrefix(“something”) / string.hasSuffix(“something”)

The hasPrefix(_:) and hasSuffix(_:) methods perform a character-by-character canonical equivalence comparison between the extended grapheme clusters in each string。

18. 编码格式: 编码格式有三种 UTF-8, UTF-16, UTF-32, 不过这部分文档的其他概念就看不太懂了,先放在这里,以后继续学习。

--

--