1、Swift入门学习笔记(第一版),对Swift的基础知识点进行梳理总结。知识点一直在变,只是作为参考,以苹果官方文档为准~
2、在学习完基本的知识点以后会结合官方文档及相关资料,在此版本的基础上进行添加更改。
五、字符串和字符
5.1、基本操作
//字符串
let dateQuestion = "The month is "
let dateNum = 10
//var dateStr = dateQuestion + dateNum //swift不支持隐式类型转换,需要显式
//字符串之间可以相加
var dateStr = dateQuestion + String(dateNum) //显式类型转换
dateStr += " bingo"
print(dateStr)
let Month = 10
let day = 19
let date = "今天是 \(Month)月\(day)日" //在OC中需要用%传入值,而swift不用
print(date)
Output:
The month is 11 bingo
今天是 11月1日
5.2、字符串字面量的特殊字符
1、转义字符\0(空字符)、\(反斜线)、\t(水平制表符)、\n(换行符)、\r(回车符)、\”(双引号)、\’(单引号)。
2、Unicode 标量,写成\u{n}(u为小写),其中n为任意一到八位十六进制数且可用的 Unicode 位码。
5.3、可扩展的字形群集
每一个 Swift 的Character类型代表一个可扩展的字形群。 一个可扩展的字形群是一个或多个可生成人类可读的字符 Unicode 标量的有序排列。
let eAcute:Character = "\u{E9}"
print(eAcute) //单一的Swift的Character值,同时代表一个可扩展的字符群
let combinedEAcute: Character = "\u{65}\u{301}"
print(combinedEAcute) //一个标准字母e加上一个急促重音的标量使其与前者相同
Output:两者得到的 结果都是“字母e的第二声”
é
é
5.4、计算字符数量
var testCount = "cafe"
print("testCount has \(testCount.characters.count) characters")
testCount += "\u{301}"
print("testCount has \(testCount.characters.count) characters")
Output:
testCount has 4 characters
testCount has 4 characters
结果是相同的。
1、可扩展的字符群集可以组成一个或者多个 Unicode 标量,则不同的字符以及相同字符的不同表示方式可能需要不同数量的内存空间来存储。所以 Swift 中的字符在一个字符串中并不一定占用相同的内存空间数量。
2、因此characters属性必须遍历全部的Unicode标量,知道范围才能确定字符串的字符数
3、同时注意characters与NSString的length属性的区别。NSString的length属性是利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展的字符群集。
5.5、字符串索引
1、startIndex
:String第一个Character的索引
2、endIndex
:最后一个Character的后一个位置的索引。后一位置!后一位置!后一位置!
3、String.Index.predecessor()
:前面一个索引
4、String.Index.successor()
:后面一个索引
5、String.Index.advancedBy()
:任意位置索引
6、characters.indices
:创建一个包含全部索引的范围
var indicesString = "Halloween!"
print(indicesString[indicesString.endIndex.predecessor()])
print(indicesString[indicesString.startIndex.successor()])
print(indicesString[indicesString.endIndex.advancedBy(-6)])
for index in indicesString.characters.indices {
print("\(indicesString[index])")
}
!
a
o
H
a
l
l
o
w
e
e
n
!
5.6、增删
1、insert(_:atIndex:)
:插入一个字符到指定索引
2、insertContentsOf(_:at:)
:插入一个字符串到自定索引
3、removeAtIndex(_:)
:删除指定索引的一个字符
4、removeRange(_:)
:删除指定索引的一个字符串
对字符串进行说明
var insertAndRemoveString = "hello"
insertAndRemoveString.insertContentsOf(" world".characters, at: insertAndRemoveString.endIndex)
print(insertAndRemoveString)
let range = insertAndRemoveString.endIndex.advancedBy(-6)..<insertAndRemoveString.endIndex
insertAndRemoveString.removeRange(range)
print(insertAndRemoveString)
Output:
hello world
hello
5.7、比较字符串
1、字符串相等(==、!=)
只要两字符串或字符的可扩展的字形群集是标准相等的,那么他们就相等。无所谓其字形群集是由不同的Unicode标量构成。
简言之就是只要语言意义和外观相同就认为他们标准相同
2、前缀后缀相等
hasPrefix(_:)/hasSuffix(_:)
,返回一个布尔值
let testStringArray = [
"Boy Zhu",
"Boy Huang",
"Boy Hu",
"Girl Juliet"]
var boyCount = 0
for info in testStringArray {
if info.hasPrefix("Boy") {
boyCount++
}
}
print("There are \(boyCount) boy")
Output:
There are 3 boy
5.8 字符串的Unicode表示形式
这部分个人认为应用的地方应该不多,有需要用到时现查~