A string String is a sequence of characters, such as "hello, world", "albatross". Strings in Swift are defined by the String keyword, and they are also a collection of some characters, defined by Character.
Swift's String and Character types provide a fast, Unicode-compatible character solution for the code. The initialization and use of String types are readable and are similar to strings in C. String can also be combined by using the + operator, and using strings is as simple as using other basic types in Swift.
1. String constants
In the code, you can use string constants predefined by String, and the definition method is very simple:
let someString = “Some string literal value”
String constants can include the following special characters:
Empty characters\0, backslash\, tab characters\t, line breaks\n, carriage return\r, double quotes\" and single quotes\'
Single-byte Unicode characters, \xnn, where nn is two hexadecimal numbers
Double-byte Unicode characters, \unnnn, where nnnn is four hexadecimal numbers
Four-byte Unicode characters, \Unnnnnnnnn, where nnnnnnnn is eight hexadecimal numbers
The following code gives examples of these four strings:
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\x24" // $, Unicode scalar U+0024
let blackHeart = "\u2665" // ♥, Unicode scalar U+2665
let sparklingHeart = "\U0001F496" // , Unicode scalar U+1F496
2. Initialize an empty string
There are two forms when initializing an empty string, but the results of both initialization methods are the same, indicating that the empty string
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
The isEmpty property can be used to check whether a string is empty
if {
println("Nothing to see here")
}
// prints "Nothing to see here"
3. Variable length string
If the string defined by the var keyword is a variable-length string that can be modified, while the string defined by the let keyword is a constant string and cannot be modified.
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
4. A string is not a pointer, but an actual value
In Swift, a String type is an actual value. When a new String is defined and the previous String value is copied over, an equal new value is actually created, rather than just pointing to the past like a pointer.
Also, when the function passes parameters, the actual value is also passed, and a new string is created. The subsequent operations will not change the original String string.
5. Characters
Swift's string String is composed of the character Character, each Character represents a specific Unicode character. Through a for-in loop, you can traverse every character in a string:
for character in "Dog!" {
println(character)
}
// D
// o
// g
// !
//
You can also define just a single character:
let yenSign: Character = "¥"
6. Character Count
Use the global function countElements to calculate the number of characters in a string:
let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
7. Use characters and strings in combination
String and Character types can be combined into a new string by adding + signs.
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1 // equals "hello!"
let stringPlusString = string1 + string2 // equals "hello there"
let characterPlusString = character1 + string1 // equals "!hello"
let characterPlusCharacter = character1 + character2 // equals "!?"
You can also use the += sign to combine:
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
var welcome = "good morning"
welcome += character1
// welcome now equals "good morning!"
8. Use strings to generate new strings
Through existing strings, you can use the following method to generate a new string:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
In the above example, first use the string 3 of multipleer as part of the new string and add it with (multiplier). At the same time, the above example also uses the type conversion Double (multiplier), adding the calculation result and the string itself as elements to the new string.
9. String comparison
Swift provides three ways to compare the values of strings: strings are equal, prefixes are equal, and suffixes are equal.
String equality
When two strings contain exactly the same characters, they are judged to be equal.
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
//Output "These two strings are considered equal"
Prefix (prefix) equals suffix (hasSuffix) equals
Use two methods of the string class hasPrefix and hasSuffix to check whether the prefix or suffix of a string contains another string. It requires a String type parameter and returns a Boolean type value. Both methods will make characters between characters between the original string and the prefix string or the suffix string.
In the following example, a string array is used to reproduce the scenes of Shakespeare's Romeo and Juliet's first two acts.
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"
]
You can use the hasPrefix method and romeoAndJuliet array to calculate how many scenes to perform in the first act.
var act1SceneCount = 0
for scene in romeoAndJuliet {
if ("Act 1 ") {
++act1SceneCount
}
}
println("There are \(act1SceneCount) scenes in Act 1")
//Output "There are 5 scenes in Act 1"
Similarly, use the hasSuffix method to calculate how many scenarios occur in Capulet Mansion and Friar Lawrence cell
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if ("Capulet's mansion") {
++mansionCount
} else if ("Friar Lawrence's cell") {
++cellCount
}
}
println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// Output "6 mansion scenes; 2 cell scenes"
uppercase and lowercase strings
You can get the uppercase or lowercase of a string from an uppercaseString and lowercaseString of a String type.
let normal = "Could you help me, please?"
let shouty =
// shouty is equal to "COULD YOU HELP ME, PLEASE?"
let whispered =
// whispered is equal to "could you help me, please?"
10、Unicode
Unicode is an international standard for encoding and representing text. It can display the standard form of almost all characters in all languages. They can also read and modify their characters from external source files such as text files or web pages.
Unicode Terms
Each Unicode character can be encoded as one or more unicode scalars. A unicode scalar is a unique 21-digit number (or name), corresponding to a character or identifier. For example U+0061 is a lowercase A ("a"), or U+1F425 is a yellow chicken facing us
When a Unicode string is written to text or other storage, the unicode scalar is encoded according to the format defined by Unicode. Each formatted encoded character is a small block of code, called code units. It contains UTF-8 format (each string consists of 8-bit code units). and UTF-16 format (each string consists of 16-bit code units)
Unicode strings
Swift supports a variety of different ways to get Unicode strings.
You can use the for-in statement to traverse the string to get the Unicode encoded value of each character. This process has been described in Working with Characters.
Alternatively, use the appropriate one in the following three descriptions to obtain the value of a string
UTF-8 character encoding unit collection uses the utf-8 attribute of String type
UTF-16 character encoding unit collection uses the utf-16 attribute of the String type
21-bit Unicode scalar collection uses unicodeScalars attribute of String type
Each of the following examples shows different encodings displayed by D , o , g , !
(DOG FACE, or Unicode scalar U+1F436) string composed of characters
UTF-8
You can use the utf8 property of type String to iterate over a UTF-8 encoded string. This property is of UTF8View type
, UTF8View is an 8-bit unsigned shaping (UInt8) set, and each byte in the set is UTF-8 encoded.
for codeUnit in dogString.utf8 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 33 240 159 144 182
In the example above, the first 4 decimal codeunit values (68,111,103,33) are displayed as strings D , o , g and ! , the same as their ASCII encoding. The values of the following 4 codeunits (240, 159, 144, 182) are 4-byte UTF-8 encodings for the DOG FACE characters.
UTF-16
You can use the utf16 attribute of type String to iterate over a UTF-16 encoded string. This property is of type UTF16View. UTF16View is a 16-bit unsigned shaping (UInt16) set. Each byte in the set is UTF-16 encoding.
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 33 55357 56374
Similarly, the first 4 decimal codeunit values (68,111,103,33) are displayed as strings D , o , g and ! , and their UTF-16 codeunit is the same as their UTF-8 codeunit.
The 5th and 6th codeunit values (55357 and 56374) are the proxy pair encodings for UTF-16 of the DOG FACE character. Their values are composed of a high-bit proxy with a value of U+D83D (decimal 55357) and a low-bit proxy with a value of U+DC36 (decimal 56374).
Unicode scalar
You can use the unicodeScalars property of type String to iterate over a Unicode scalar encoded string. This property is the UnicodeScalarsView type, which is a collection of UnicodeScalar types. Each Unicode scalar is an arbitrary 21-bit Unicode code bit, without a high-bit proxy, and without a low-bit proxy.
Each UnicodeScalar uses the value attribute, returning the 21-bit value of the scalar, and each bit is a 32-bit unsigned shaping (UInt32):
for scalar in {
print("\() ")
}
print("\n")
// 68 111 103 33 128054
The value attribute is once again displayed in the first 4 UnicodeScalar values (68,111,103,33) encoded characters D , o , g and ! . The fifth and last UnicodeScalar is the DOG FACE character, with a decimal of 128054, equivalent to 1F436 in hexadecimal, equivalent to U+1F436 in Unicode scalar.
Each UnicodeScalar can be constructed as a new string instead of reading their value attributes, similar to inserting a string.
for scalar in { println("\(scalar) ") }
// D
// o
// g
// !
//