//一、字符串文字
//使用字符串文字作为常量或变量的初始值:
let someString = "Some string literal value"
//1.多行字符串文字
//如果字符串需要跨越多行的,请使用多行字符串字面量——由三个双引号包围的字符序列:
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."
"""
//多行字符串文字包括其左引号和右引号之间的所有行。字符串从左引号 (""")之后的第一行开始,到右引号之前的行结束
//当您的源代码在多行字符串文字中包含换行符时,该换行符也会出现在字符串的值中。
//如果您想使用换行符使源代码更易于阅读,但又不希望换行符成为字符串值的一部分,请在这些行的末尾写一个反斜杠\:
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."
"""
//要制作以换行开头或结尾的多行字符串文字,请在第一行或最后一行写一个空行。例如:
let lineBreaks = """
This string starts with a line break.
It also ends with a line break.
"""
//多行字符串可以缩进以匹配周围的代码。右引号(""")之前的空格告诉Swift在所有其他行之前要忽略的空格。
//如果除了右引号之前的内容之外,在行的开头还写有空格,则该空格会被包括在内。
//其他行前的空格不能少于右引号之前的空格
let linesWithIndentation = """
This line doesn't begin with whitespace.
This line begins with four whitespace.
This line doesn't begin with whitespace.
"""
//2.字符串文字中的特殊字符
//字符串文字可以包含以下特殊字符:
//转义的特殊字符\0(空字符)、\(反斜杠)、\t(水平制表符)、\n(换行)、\r(回车)、"(双引号)和'(单引号)
//任意的Unicode标值,写为\u{Ñ},其中Ñ是一个1-8位十六进制数(统一在讨论的Unicode下文)
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// $, Unicode scalar U+0024
let dollarSign = "\u{24}"
// ♥, Unicode scalar U+2665
let blackHeart = "\u{2665}"
// 💖, Unicode scalar U+1F496
let sparklingHeart = "\u{1F496}"
//因为多行字符串文字使用三个双引号而不是一个,所以您可以在多行字符串文字中包含一个双引号而无需转义它。
//要将文本字符串中包含"""的,请至少对其中一个引号进行转义
let threeDoubleQuotationMarks = """
Escaping the first quotation mark \"""
Escaping all three quotation marks \"""
"""
print(threeDoubleQuotationMarks)
//3.扩展字符串分隔符
//您可以将字符串文字放置在扩展分隔符中,以在字符串中包含特殊字符而不调用它们的效果。
//将字符串放在引号(")内并用数字符号(#)括起来。
//例如,打印字符串文字会打印换行转义序列,而不是跨两行打印字符串。
let printOriginString = #"Line 1\nLine 2"#
print(printOriginString)
//使用扩展分隔符创建的字符串文字也可以是多行字符串文字。
//您可以使用扩展分隔符将文本包含在多行字符串"""中,覆盖文本的默认行为。
let threeMoreDoubleQuotationMarks = #"""
Here are three more double quotes: """
"""#
print(threeMoreDoubleQuotationMarks)
//4.初始化空字符串
// these two strings are both empty, and are equivalent to each other
var emptyString = ""
var anotherEmptyString = String()
//String通过检查它的isEmpty属性来确定一个值是否为空
if emptyString.isEmpty {
print("Nothing to see here")
}
//5.字符串可变性
// 变量可以修改
var variableString = "Horse"
variableString += " and carriage"
//常量不可以修改
let constantString = "Highlander"
//constantString += " and another Highlander"
//6.字符串是值类型
//Swift中的String类型是值类型
//7.字符(Character)
//可以通过使用循环遍历字符串来访问字符串中的各个Character值
for character in "Dog!🐶" {
print(character)
}
//可以通过Character提供类型注释创建独立常量或变量:
let exclamationMark: Character = "!"
//可以通过将一组Character值作为参数传递给String,来构造其字符串初始化程序值:
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
//8.连接字符串和字符
//String可以使用加法运算符(+),将值相加(或连接)以创建新String值:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
//还可以使用加法赋值运算符(+=)将String值附加到现有String变量:
var instruction = "look over"
instruction += string2
//可以使用String类型的方法append()将Character值附加到变量String上
let exclamationMarkAppend: Character = "!"
welcome.append(exclamationMarkAppend)
//9.字符串插值
//字符串插值是一种通过将String常量、变量、文字和表达式的值包含在字符串文字中来构造新值的方法。
//您可以在单行和多行字符串文字中使用字符串插值。
//您插入到字符串文字中的每个项目都包含在一对括号中,并以反斜杠()为前缀
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
//要在使用扩展分隔符的字符串内使用字符串插值,请将反斜杠后的数字符号数量与字符串开头和结尾的数字符号数量匹配
let insertString = #"6 times 7 is \#(6 * 7)."#
//二、字符计数
//要检索字符串中Character值的计数,请使用字符串的count属性:
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.count) characters")
//三、访问和修改字符串
//可以通过字符串的方法和属性或使用下标语法来访问和修改字符串。
//1.字符串索引
//每个String值都有一个关联的索引类型,String.Index对应于每个值Character在字符串中的位置
let greeting = "Guten Tag!"
// G
greeting[greeting.startIndex]
// !
greeting[greeting.index(before: greeting.endIndex)]
// u
greeting[greeting.index(after: greeting.startIndex)]
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
//2.插入和移除
//要将单个字符插入到指定索引处的字符串中,请使用insert(_:at:)方法,
//而要在指定索引处插入另一个字符串的内容,请使用insert(contentsOf:at:)方法。
var welcomeString = "hello"
// welcomeString now equals "hello!"
welcomeString.insert("!", at: welcomeString.endIndex)
// welcomeString now equals "hello there!"
welcomeString.insert(contentsOf: " there", at: welcomeString.index(before: welcomeString.endIndex))
//要从指定索引处的字符串中删除单个字符,请使用remove(at:)方法
//要删除指定范围内的子字符串,请使用该removeSubrange(_:)方法
//welcomeString now equals "hello there"
let removeCharacter = welcomeString.remove(at: welcomeString.index(before: welcomeString.endIndex))
let range = welcomeString.index(welcomeString.endIndex, offsetBy: -6)..<welcomeString.endIndex
//welcomeString now equals "hello"
welcomeString.removeSubrange(range)
//3.子串(Substrings)
let greetingSubstrings = "Hello, world!"
let substringsIndex = greetingSubstrings.firstIndex(of: ",") ?? greetingSubstrings.endIndex
// beginning is "Hello"
let beginning = greetingSubstrings[..<substringsIndex]
// Convert the result to a String for long-term storage.
let newString = String(beginning)
//四、比较字符串
//Swift 提供了三种比较文本值的方法:字符串和字符相等、前缀相等和后缀相等。
//1.字符串和字符相等
//字符串相等检查可以用“等于”运算符(==)和“不等于”运算符(!=)
let equalString = "We're a lot alike, you and I."
let sameEqualString = "We're a lot alike, you and I."
if equalString == sameEqualString {
print("These two strings are considered equal")
}
//备注:
//如果两个String值(或两个Character值)的扩展字素簇在规范上等效则认为它们相等。
//如果扩展的字素簇具有相同的语言含义和外观,则它们在规范上是等效的,即使它们在是由不同的Unicode编码组成。
// "Voulez-vous un café?" using LATIN SMALL LETTER E WITH ACUTE
let eAcuteQuestion = "Voulez-vous un caf\u{E9}?"
// "Voulez-vous un café?" using LATIN SMALL LETTER E and COMBINING ACUTE ACCENT
let combinedEAcuteQuestion = "Voulez-vous un caf\u{65}\u{301}?"
if eAcuteQuestion == combinedEAcuteQuestion {
print("These two strings are considered equal")
}
//2.前缀和后缀相等
//要检查字符串是否具有特定的字符串前缀或后缀,请调用字符串的hasPrefix(:)和hasSuffix(:)方法
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
//您可以使用hasPrefix(_:)方法来计算romeoAndJuliet数组的中第1幕的场景数:
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
act1SceneCount += 1
}
}
// Prints "There are 5 scenes in Act 1"
print("There are \(act1SceneCount) scenes in Act 1")
//使用该hasSuffix(_:)方法计算发生在凯普莱特宅邸和劳伦斯修士牢房内或周围的场景数量:
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
mansionCount += 1
} else if scene.hasSuffix("Friar Lawrence's cell") {
cellCount += 1
}
}
// Prints "6 mansion scenes; 2 cell scenes"
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
//五、字符串的 Unicode 表示
//1.UTF-8 表示
let dogString = "Dog‼🐶"
// Prints "68 111 103 226 128 188 240 159 144 182 "
for codeUnit in dogString.utf8 {
print("\(codeUnit) ", terminator: "")
}
print("")
//2.UTF-16 表示
// Prints "68 111 103 8252 55357 56374 "
for codeUnit in dogString.utf16 {
print("\(codeUnit) ", terminator: "")
}
print("")
//3.Unicode 标量表示
// Prints "68 111 103 8252 128054 "
for scalar in dogString.unicodeScalars {
print("\(scalar.value) ", terminator: "")
}
print("")
for scalar in dogString.unicodeScalars {
print("\(scalar) ")
}