- 字符串 (String Literals)
let someString = "Some string literal value"
- 多行字符串 (Multiline String Literals)
- 初始化空字符串 (Initializing an Empty String)
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
通过检查其布尔值isEmpty
属性,判断String
值是否为空:
if emptyString.isEmpty {
print("Nothing to see here")
}
// Prints "Nothing to see here"
- 字符串可变性 (String Mutability)
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified
NOTE
这种方法与Objective-C
和Cocoa
中的字符串可变不同,您可以在两个类(NSString
和NSMutableString
)之间进行选择,以指示字符串是否可变。
- 字符的使用 (Working with Characters)
for character in "Dog!🐶" {
print(character)
}
// D
// o
// g
// !
// 🐶
let exclamationMark: Character = "!"
可以通过将Character值数组作为参数传递给其初始化程序来构造字符串值:
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"
- 连接字符串和字符 (Working with Characters)
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
NOTE
您不能将字符串或字符附加到现有的Character
变量,因为Character
值只能包含单个字符。
let badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// Prints two lines:
// one
// twothree
let goodStart = """
one
two
"""
print(goodStart + end)
// Prints three lines:
// one
// two
// three
- 字符串插入 (String Interpolation)
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
- 字符串计算 (Counting Characters)
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.count) characters")
// Prints "unusualMenagerie has 40 characters"
- 访问和修改字符串 (Accessing and Modifying a String)
1.字符串索引
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
尝试访问字符串范围之外的索引或字符串范围之外的索引处的字符将触发运行时错误。
greeting[greeting.endIndex] // Error
greeting.index(after: greeting.endIndex) // Error
使用indices
属性可以访问字符串中各个字符的所有索引。
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n T a g ! "
2.字符串的插入和移除
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
要从指定索引处的字符串中删除单个字符,请使用remove(at :)方法,并删除指定范围内的子字符串,请使用removeSubrange(_ :)方法:
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
- 字符串子集 (Substrings)
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"
// Convert the result to a String for long-term storage.
let newString = String(beginning)
image.png
- 字符串比较 (Substrings)
1.字符串和字符相等
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
print("These two strings are considered equal")
}
// Prints "These two strings are considered equal"
2.前缀和后缀等式
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
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"
类似地,使用hasSuffix(_ :)
方法计算在Capulet
的豪宅和Friar Lawrence
的单元格中或周围发生的场景数量:
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
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// Prints "6 mansion scenes; 2 cell scenes"
Note
hasPrefix(_ :)
和hasSuffix(_ :)
方法在每个字符串中的扩展字形集群之间执行逐字符规范等效性比较,如字符串和字符等式中所述。
网友评论