字符串字面量
Swift 的字符串是值类型,采用 Unicode 编码。
字符串用一对双引号括起来,类型为String
。
let someString = "Some string literal value"
如果字符串需要跨行,可以用三个双引号括起来。
let softWrappedQuotation = """
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."
"""
结尾的\
表示这里不换行。结尾的"""
前面如果有 n 个空格,那么该多行字符串每一行前面都会忽略 n 个空格。
字符串中以\
开头的被称为转义字符,如空字符\0
、反斜杠\\
、水平制表符\t
、换行符\n
、回车符\r
、双引号"
、单引号'
等。\u{n}
表示任意 Unicode 字符,其中n
是 1~8 个 16 进制数字。
如果在引号前后都加上#
,字符串中的转移符号就不会生效。但如果转义符号后面也有#
,则该转义字符仍然会生效。
#"Line1\nLine2\#Line3"#
// Line1\nLine2
// Line3
初始化空字符串
用""
或String()
创建空字符串,isEmpty
属性检查字符串是否为空。
var emptyString = String()
if emptyString.isEmpty {
print("Nothing in emptyString")
}
操作字符
使用for
来遍历字符串中的每个字符。
for ch in "Hello" {
print(ch)
}
创建一个独立的字符常量或变量:
let ch: Character = "!"
通过字符数组创建字符串:
let chList: [Character] = ["C", "a", "t"]
let chString = String(chList) // Cat
count
属性获取字符串的长度。
使用+
将两个字符串连接,+=
在已有的字符串后面追加字符串,append()
在末尾追加字符。
使用\()
将变量的值插入到字符串中。
访问和修改字符串
字符串无法通过整数来索引,只能使用startIndex
属性获取字符串首个字符的位置,或用endIndex
属性获取字符串最后一个字符之后的位置。index(before:)
和index(after:)
方法访问给定索引的前后,如果是更远的索引,使用index(_:offsetBy:)
方法。
let greeting = "Guten Tag!"
print(greeting[greeting.startIndex]) // G
print(greeting[greeting.index(before: greeting.endIndex)]) // !
print(greeting[greeting.index(after: greeting.startIndex)]) // u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
print(greeting[index]) // a
indices
属性访问字符串的每个字符的索引:
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
插入和删除
使用insert(_:at:)
插入字符,insert(contentsOf:at:)
插入字符串。
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
使用remove(at:)
删除字符,removeSubrange(_:)
删除一段字符。
welcome.remove(at: welcome.index(before: welcome.endIndex))
let range = welcome.index(welcome.endIndex, offsetBy: =6)..<welcome.endIndex
welcome.removeSubrange(range)
子字符串
用[]
获取的是字符串的映射,要将其保存为真正的字符串需要用String()
:
let greeting = "Hello, world!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index] // Hello
let newString = String(beginning)
字符串比较
两个字符串或字符可以用==
和!=
来比较。两个字符可能字型一致但 Unicode 编码不一致,它们也被认为是不等的。
hasPrefix()
和hasSuffix()
检查字符串是否具有特定的字符串前缀或后缀。