Strings and Characters
String Literals
Multiline String Literals
a single line String can be initialized by a pair of double quotation marks(" ")
But a multiline String should be initialized by a pair of three double quotation marks(""" """)。
let singleLineString = "These are the same."
let multilineString = """
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."
"""
and for multiline String, we can use a backslash() to make it easier to read.
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."
"""
Special Characters in String Literals
An arbitrary Unicode scalar value, written as \u{n}, where n is a 1–8 digit hexadecimal number.
let dollarSign = "\u{24}" // $, Unicode scalar U+0024
let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496
but swift can support the Unicode as String directly, so this rarely to use.
Extended String Delimiters
if you use “#” this sign to surround the String, you can print a string without any effect.
let string = #"Line1 \n Line2"# // print "Line1 \n Line2" will not being wrapped
but if you want to make effect anyway, you can try this:
let string = #"Line1 \n Line2 \#n Line3"#
/*print "Line1 \n Line2
Line3"
will being wrapped before Line3
*/
Initializing an Empty String
An empty String means that the string dosen’t have length.
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
print(emptyString.isEmpty) // is true
print(anotherEmptyString.isEmpty) // is true
Strings Are Value Types
String will alway be copied to another one when it’s assigned or passed to a function or method.
Concatenating Strings and Characters
For multiline string, interesting, just for example:
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
Accessing and Modifying a String
String Indices
Get indices of String:
First, we can get the first and last index with those properties:
startIndex
endIndex
Then, we can use those function to get each other indices:
index(before:)
index(after:)
index(_:offsetBy:)
For example:
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
If the index outside of a string’s range, we will get a runtime error:
greeting[greeting.endIndex] // Error
greeting.index(after: greeting.endIndex) // Error
we can for-each indices:
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n T a g ! "
Inserting and Removing
-
insert(_:at:)
//insert a charactor into a string at a specific index -
insert(contentsOf:at:)
//insert a string into a string from a specific index -
remove(at:)
//remove a charactor from a string at a specific index -
removeSubrange(_:)
//remove a string from a string at a specific range
For example:
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!"
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
Substrings aren’t suitable for long-term storage—because they reuse the storage of the original string.
When you’re ready to store the result for a longer time, you convert the substring to an instance of String.
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)
Let’s think!