English version of PDFhttp://download.csdn.net/detail/tsingheng/7480427
if emptyString.isEmpty {
println("Nothing to see here")
}
// prints "Nothing to see here"
3. String variability
You can decide whether or not he can be changed by assigning a string object to a constant or variable.
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 this is different from the way in which the string can be changed in OC, which is expressed by using NSString and nsmutablestring.
4. String is a value type
Swift's string is a value type. Suppose you create a string and assign a value to a function or method when it is passed, or assign to another constant or variable to copy it again. In these cases, a new string is created based on the original string, with the new string being used when passing the parameter or assigning the value.
NOTE This feature is not the same as Cocoa's nsstring. Suppose you create a NSString object in cocoa, and then pass it to a function or method or assign to another variable, pass or assign a reference to the object, and do not create a new string unless you display the need.
This feature of Swift ensures that a function or method gets the string that it passed, without having to control where the string comes from. And don't worry about the string being changed by someone else, only I can change it myself.
Behind these scenes, the Swift compiler optimizes the use of strings, only to replicate when there is a real need to replicate them. That means you always get very good performance when you use a string of value type.
5. Using characters
Swift's string represents an ordered collection of a set of characters.
Each character character value represents a single Unicode. You can use for-in traversal to get individual characters in a string:
For character in "Dog! Expressions can't be displayed" {
Println(character)
}
// D
// o
// g
// !
// The expression can't be displayed
Or you can use string literals of a single character to create a character type constant or variable such as let Yensign:charactor = "¥"
6. Character Count
If you want to query the number of characters inside a string, you can call the global function countelements and pass the string as a parameter
Let unusualMenagerie = "Koala expression, Snail <span style="font-family: Arial, Helvetica, sans-serif;">expression</span>, Penguin expression, Dromedary expression"
Println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
NOTE for the same Unicode character, the memory size required for different Unicode strings and different representations is not the same.
So the memory used by each character in the string is not the same. So the length of the string cannot be computed by traversing each character sequentially. Assuming you use a particularly long string, note that the Countelements function iterates through the characters in the string to calculate the number of characters.
Also note that the result returned by the Countelements function is not always equal to the length property of the corresponding nsstring. The length property of NSString is the number of 16-bit units in a string based on the UTF-16 form. Rather than the number of Unicode characters in the string.
Swift's string type corresponds to the length of NSString, which is the Utf16count property.
7. Connection strings and characters
strings and characters can be concatenated using a plus sign to form a new string
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 append a string or character to an existing string variable using the + = operator
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
var welcome = "good morning"
welcome += character1
// welcome now equals "good morning!"
NOTE You cannot append a string or character to a character, because the character type can only include a single character.
8. String filling
String fills can be done by adding a constant variable to the mix in a string literal. Literal and expression to create a new string value. Each object that increments the string literal is prefixed with a pair of parentheses and a backslash:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
The value of multiplier in the above seniority is inserted in the form of \ (multiplier) into string literals. This place will be replaced with the actual value of the multiplier to create an actual string when the string has been computed.
Multiplier after the string is still part of an expression. This expression evaluates the value of double (multiplier) *2.5 and inserts the result 7.5 into the string.
Here the expression is written \ (Double (multiplier) *2.5) in the string literal.
NOTE An expression that fills in a string constant in such a way cannot include an escaped double-or backslash, or a carriage return or a newline.
9. Comparison of strings
Swift provides three ways to compare strings: equal, prefix equal, and suffix equal
Equal
Suppose that two strings contain the same characters and that the same sort is considered 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"
prefixes equal and suffix equal
Suppose you want to check whether a string has a special prefix and suffix, call the Hasprefix and Hassuffix methods of the string, and two methods have a string type parameter. Returns a Boolean value.
Each of the two methods makes a one-character comparison of the original string with the prefix string or suffix string. The effect should be the same as Java Startwith and Endwidth.
The following example takes the place of the first two Acts Romeo and Juliet as an array:
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 on the Remeoandjuliet array to calculate the first act of a couple of
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
println("There are \(act1SceneCount) scenes in Act 1")
// prints "There are 5 scenes in Act 1"
The same reasoning can be used hassuffix to calculate a few shots near Capulets mansion and Lawrence's cell.
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet‘s mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence‘s cell") {
++cellCount
}
}
println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// prints "6 mansion scenes; 2 cell scenes"
10. String letters uppercase and lowercase conversions
You can obtain the corresponding uppercase or lowercase version number by using the Uppercasestring and LowerCaseString properties of the string:
Let normal
let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty is equal to "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered is equal to "could you help me, please?
"
11.Unicode
Unicode is an international standard for encoding and representing text. He can let you use a standard form to represent whatever character in any language. Read or write these characters from external sources such as text files or Web pages.
Swift's string and character types are fully compatible with the Unicode standard.
They support several different Unicode encodings.
Unicode terminology
Each character in Unicode can be represented as not one or more Unicode scalars. A Unicode scalar is a unique 21-digit number for a corresponding character or expression, such as u+0016 the corresponding lowercase Latin letter A. Or u+1f425 represents the emoji xxx.
When a Unicode string is written to a text file or otherwise stored, these Unicode scalars are encoded in a Unicode format.
Each format encodes a string into chunks, which is the code unit. These formats contain the UTF-8 format (using a 8-bit code unit encoded string), UTF-16 format (using 16-bit code units to encode strings).
Unicode notation for strings
Swift provides several different ways to use the Unicode notation of strings.
You can use the For-in statement to traverse the individual characters of a string as Unicode characters.
Or. You can obtain a string by using one of the following three types of Unicode-compliant notation.
UTF-8 code unit Collection (via String's UTF8 property)
UTF-16 code unit Collection (via String's Utf16 property)
21-bit Unicode scalar value collection (via the Unicodescalars property of the string)
The following example lists a variety of different representations, string characters d,o,g,!, and emoji dog characters (not shown here.) Unicode scalar u+1f436)
Let dogstring = "dog! dog";
UTF-8
You can get the UFT-8 notation by traversing the UTF8 property of the string. This property returns the Utf8view type. is a collection of UInt8 values.
Each byte inside the string performs a sample example of the following:
For CodeUnit in Dogstring.utf8 {
print ("\ (codeUnit)")}print ("\ n")
//68 111 103 33 240 159 144 182
The first four digits of the above sample codeunit value is 68,111,103,33 represents the character D. O. G, and!, the UTF-8 representation of these characters is the same as the ASCII representation.
The last four codeunit values are 240,159,144,182 is the four-byte representation of the dog's expression character.
UTF16
You can get the UTF16 notation by traversing the Utf16 property of the string. This property returns the Utf16view type, which is a collection of UInt16 values. Each byte inside the string performs a sample example of the following:
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 33 55357 56374
The first four numbers are the same. 68,111,103,33. Represents the character d,o,g,!. The UTF-16 code unit of these characters is the same as the UTF-8 notation.
The last two values are 55357 and 56374 are UTF-16 representations of the dog's expression characters. The values u+d83d and U+DC36 are respectively represented.
Unicode scalar
You can get a Unicode scalar representation by traversing the Unicodescalars property of a string.
The result returned by this property is the Unicodescalarview type, which is a collection of unicodescalar values. Unicodescalar is no matter what the 21-bit non-pre-replacement or post-replacement code.
Each unicodescalar has a property that can return its own 21-bit value. The result is expressed using the UInt32 value.
for scalar in dogString.unicodeScalars {
print("\(scalar.value) ")
}
print("\n")
// 68 111 103 33 128054
The first four Value property settings are either 68,111,103 or 33. The last 128054 is the hexadecimal number 1f436. is exactly the Unicode scalar u+1f436 of the dog's expression character.
There is also a second way to get the value property of Unicodescalar, which is to use this character to create a new string value, such as a string fill:
For scalar in dogString.unicodeScalars {
Println("\(scalar) ")
}
// D
// o
// g
// !
// dog expression
The end of this chapter. The following Chapter address: 6. Collection Properties
5.Swift Tutorial Translation Series--swift strings and characters