1.字面量:"haha",这就是一个字面量,双引号包裹,具有固定顺序的字符集,六个双引号可以实现多行字符串字面量
2.多行时,回车是换行,\是本行续行符
3.转义字符 \0(空字符)、\\(反斜线)、\t(水平制表符)、\n(换行符)、\r(回车符)、\"(双引号)、\'(单引号)
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
4.Unicode 标量,写成 \u{n}(u 为小写),其中 n 为任意一到八位十六进制数且可用的 Unicode 位码()
let sparklingHeart = "\u{1F496}" // 💖,Unicode 标量 U+1F496
5.由于多行字符串字面量使用了三个双引号,而不是一个,所以你可以在多行字符串字面量里直接使用双引号(")而不必加上转义符(\)。要在多行字符串字面量中使用 """ 的话,就需要使用至少一个转义符(\):
let threeDoubleQuotes = """
Escaping the first quote \"""
Escaping all three quotes \"\"\"
"""
6.初始化空字符串:var emptyString = "" 、var anotherEmptyString = String(),下面判空isEmpty
if emptyString.isEmpty {
print("Nothing to see here")
}
7.字符串可变性
var variableString = "Horse"
variableString += " and carriage"
8.字符串的常见使用
for character in "Dog!🐶" { // 遍历字符串
print(character)
}
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2 // 字符串拼接
let exclamationMark: Character = "!" // 单个字符
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString) // // 打印输出:“Cat!🐱” // 字符串拼接
var instruction = "look over"
instruction += string2 // 字符串拼接
let exclamationMark: Character = "!"
welcome.append(exclamationMark) // 字符串拼接
string.count、string.index、string.startIndex、string.endIndex
9.通过调用 String 的 index(before:) 或 index(after:) 方法,可以立即得到前面或后面的一个索引。你还可以通过调用 index(_:offsetBy:) 方法来获取对应偏移量的索引,这种方式可以避免多次调用 index(before:) 或 index(after:) 方法。
10.使用 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符。
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
11.插入和删除
你可以使用 insert(_:at:)、insert(contentsOf:at:)、remove(at:) 和 removeSubrange(_:) 方法在任意一个确认的并遵循 RangeReplaceableCollection 协议的类型里面,如上文所示是使用在 String 中,你也可以使用在 Array、Dictionary 和 Set 中。
insert(_:at:) 在一个字符串的指定索引插入一个字符
insert(contentsOf:at:) 在一个字符串的指定索引插入一个段字符串
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex) // welcome 变量现在等于 "hello!"
welcome.insert(contentsOf:" there", at: welcome.index(before: welcome.endIndex)) // welcome 变量现在等于 "hello there!"
remove(at:) 在一个字符串的指定索引删除一个字
removeSubrange(_:) 在一个字符串的指定索引删除一个子字符串
welcome.remove(at: welcome.index(before: welcome.endIndex)) // welcome 现在等于 "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex welcome.removeSubrange(range) // welcome 现在等于 "hello"
未完待续。。。
网友评论