Painted levels: being fostered fostered fostered

Tags: “iOS” “Swift 5.1” “String” author: Mu Ling Luo Review: QiShare team


String A string is a series of characters. The Swift String is represented by the String type. 1. Use string literals as initial values for constants or variables:

Let STR = "I am zhangfei"// STR system uses the type inferred to be StringCopy the code

2. Multi-line string: A sequence of characters surrounded by three double quotation marks (“”). Note: The delimiter “”” must start and end the body of a multi-line string literal on a single line.

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 multilineString = """
These are the same.
"""
Copy the code

When a multiline string literal contains a newline character, that newline character also appears in the string value. If you want to use line breaks to simplify code reading, but do not want them to be part of the string value, write a backslash \ at the end of these lines.

/* Without backslash \ print: 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." Add backslash \ print: 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 ontill 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." """ print(softWrappedQuotation)Copy the code

Special characters in a string A string can contain the following special characters:

  • Escaped special characters\ 0(null character),\ \(backslash),\ tHorizontal TAB,\ n(newline character),\ r \ n(Carriage return),\"(double quotes) and\ '(single

Quotes).

  • An arbitrary Unicode scalar value, written as\ u {n}, includingnThe value is a hexadecimal number of 1 to 8 digits.

Examples of special characters:

Let name = "I am \" zhangfei \"" let dollarSign = "\u{24}" // $, Unicode scalar u +0024 let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665 let sparklingHeart = "\ U {1F496}" // 💖, Print (name+dollarSign+blackHeart+sparklingHeart)//! < I am "Zhang Fei "$♥💖Copy the code

Because multiline string literals use three double quotes “” instead of one “, multiline string literals that contain double quotes “do not need to be escaped. But to include “” in a multi-line string, you need to escape at least one quotation mark.

let threeDoubleQuotationMarks = """
Escaping the first quotation mark \"""
Escaping all three quotation marks \"\"\"
"""
Copy the code

Extended string delimiters: We can place strings containing special characters in extension delimiters to make the contained special characters (such as escape characters) invalid. Enclose the string in quotes “and the numeric symbol #. There is no limit to the number of #, but the number needs to be consistent. Let STR = #”Line 1\nLine 2″# instead of printing a two-line string, let STR = #”Line 1\nLine 2″# If you want the special effect of a special character in a string, you need to use the numeric symbol # after the escape character \, but pay attention to the number of matches. For example, if the string: let STR = #”Line 1\#nLine 2″#, we need the newline character \n to work, we can use let STR = #”Line 1\#nLine 2″# instead. Similarly, let STR = ##”Line 1\###nLine 2″## or let STR = ###”Line 1\###nLine 2″### Multi-line strings use the extension delimiter instead of the escape character \, for example:

let threeQuotationMarks = #""" Here are three more double quotes: """ """# print(threeQuotationMarks)//! < log:Here are three more double quotes: """Copy the code

Initialize an empty String: You can specify an empty String to a variable, or initialize a String instance using the syntax used to initialize a String:

Var emptyString = "" var anotherEmptyString = String()Copy the code

String null:

If emptystring. isEmpty {print(" emptyString ")}Copy the code

** Mutable string: ** Assigns a specific string to a variable or constant to indicate whether the string can be modified. Assign a specific string to a variable: It can be modified in this case.

var variableString = "Horse"
variableString += " and carriage"
print(variableString)
Copy the code

Assign a particular string to a constant: it cannot be modified in this case.

let constantString = "Highlander" constantString += " and another Highlander"//! < compiler error: constantString is constant immutableCopy the code

In this way, unlike string mutable in Objective-C and Cocoa, you can choose between two classes, NSString and NSMutableString, to distinguish mutable strings.

Strings are value types: Swift’s String type is a value type. If we create a new string a, the value of string A is copied when we pass it to a function or method, or assign it to a constant or variable. In each case, a new copy of the existing string is created and passed or assigned instead of the original string. Swift’s default behavior of copying strings ensures that when a string is passed in a function or method, the value of the string will not be changed, no matter where it came from, unless we modify it ourselves. At the same time, Swift’s compiler optimizes the default string copy behavior: the actual copy is performed only when absolutely necessary, ensuring performance.

Character usage: We can access individual characters in a string by iterating through the string with a for-in loop.

let str = "Dog!"
for character in str {
    print(character)
}
Copy the code

Create a constant or variable of type Character

Let character: character = "" print(character) Character = "" character = "" print(character)Copy the code

Generate a string from an array of characters

let catCharacters : [Character] = ["c","a","t","i","s",""]
let catString = String(catCharacters)
print(catString)
Copy the code

Concatenate strings and characters: Strings can be concatenated together using the addition operator + to create a new string:

let string1 = "hello"
let string2 = " there"
let welcome = string1 + string2
print(welcome)
Copy the code

Use the plus assignment operator += :

var instruction = "look over" let string2 = " there" instruction += string2 //! < log:look over thereCopy the code

Add a Character value to a String variable using the String append() method.

var character : Character = "" character = "" var instruction = "look over" let string2 = " there" instruction += string2 instruction.append(character) //! < look over thereCopy the code

To construct a string of more lines using a multi-line string literal, you want every line in the string to end with a newline, including the last line.

Let badStart = """ one two """ let end = """ three """ One twothree */ print(badStart + end) let goodStart = """ one two """ /* Print three lines: The last line of goodStart ends with a newline. one two three */ print(goodStart + end)Copy the code

String interpolation: String interpolation is a method of constructing new strings by mixing constants, variables, literals, and expressions in a string. What it does: Includes the name of a constant or variable in a longer string as a placeholder and prompts Swift to replace it with the current value of the constant or variable. Use form: Enclose the name in parentheses and escape it \(variable or constant) with a backslash before the opening parenthesis. String interpolation can be used for both single-line and multi-line strings.

Let multiplier = 3 let message = "multiplimultiplier) times 2.5 is \(Double(multiplier) * 2.5)" print(message)// < 3 times 2.5 is 7.5Copy the code

Multipliers \(multiplier) and \(Double(multiplier) * 2.5) are string interpolations.

print(#"Write an interpolated string in Swift using \(multiplier)."#)//! <Write an interpolated string in Swift using \(multiplier).Copy the code

In the above example, the extended string delimiter is used to create strings containing the special character \ that would otherwise be treated as string interpolation. To use string interpolation in strings with extended separators, match the number of # symbols after \ with the number of # symbols at the beginning and end of the string.

print(#"Write an interpolated string in Swift using \#(multiplier)."#)//! <Write an interpolated string in Swift using 3.Copy the code

**Unicode: ** It is an international standard for cross-language and cross-platform text conversion and processing. The string and character types in Swift are fully Unicode compliant.

  1. Unicode scalars: Swift’s native String type is built from Unicode scalars. Unicode scalar: a character or modifier represented by 21 binary bits, (Note: Currently, the Unicode encoding range is up to 21 bits. The Unicode scalar range is 0x0000-0x10FFFF, and the binary bit is 1 0000 1111 1111 1111 1111. For example,U+ 0061 represents a,U+1F425 represents 🐥. Note that Unicode scalars do not need to assign all 21 bits to characters or modifiers, and some of the extra Unicode scalars will be retained for future assignment or for UTF-16 encoding (Note: Utf-16 is one of the uses of Unicode that maps abstract code points from the Unicode character set to 16-bit sequences for data storage or transmission.

  2. Extended glyph cluster: Each instance of Swift’s Character type, representing an extended glyph cluster. An extended glyph cluster is a sequence of one or more combinable Unicode scalars that, when combined, produce a single human-readable character. The letter e can be represented as a single Unicode scalar \u{00E9}. The letter E can also be represented as a pair of scalars: the standard letter e:\u{0065} and the sharp note \u{301}. (The tonal scalar is graphically applied to the scalar preceding it, converting E to E when it is rendered by a Unicode-aware text rendering system)

In both cases, the letter E is represented as a Character value in a single Swift, representing an extensible glyph cluster. In the first case, a single scalar in the cluster; In the second case, it is a cluster of two scalars:

Let eAcute: Character = "\u{E9}" // let combinedEAcute: Character = "\u{65}\u{301}" // e print(String(eAcute)+String(combinedEAcute))Copy the code

Extensible glyph clusters are a flexible way to represent many complex script characters as single character values.

Let precomposed: Character = "\u{D55C}" // let decomposed: Character = "\ u {1112} \ u {1161} \ u ab} {11" / / / u {1112} : ᄒ, \ {1161} : u ᅡ, \ u ab} {11: ᆫ - > 한 print (String (precomposed) + String (decomposed))Copy the code

Unicode scalars of locale designators can be combined in pairs to produce a single character value, such as a combination of the locale designator symbol U (U + 1F1FA) and the locale designator letter S (U + 1F1F8) :

Let regionalIndicatorForUS: Character = "\u{1F1FA}\u{1F1F8}" print(String(regionalIndicatorForUS) //log:🇺🇸Copy the code

** Retrieves the number of characters in a string, using the count attribute of the string:

Let title = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪" print("title with \(title. Count) ")//! < 40 charactersCopy the code

Note that the string concatenation extension glyph cluster in Swift may not affect the number of characters in the string. Such as:

var x = "thing" //! < x.count = 5 x += "\u{301}" //! The < x: thin ǵ print (x) / /! < x.ount is still 5Copy the code

An extended glyph cluster can consist of multiple Unicode scalars. This means that different representations of the same character may require different amounts of memory to store. Therefore, in Swift, each character of a string may have a different size in memory. Note that if the string is particularly long, using the count attribute to get the number of characters in the string will traverse the entire string of Unicode scalars. The count attribute may not be the same as the number of characters returned by the length attribute of an NSString that contains the same character. Because they are calculated against a different baseline. The length of an NSString is based on the number of 16-bit codes in the UTF-16 representation of the string, not on the number of Unicode extendable glyphs in the string.

// The number of characters calculated in OC. NSString * STR = @"Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"; NSLog(@"%ld",str.length); / /! < 44 charactersCopy the code

Access and modify strings: Access and modify strings using corresponding methods and attributes or using subscript syntax. String Index: Each String value has an associated Index of type String.index, which corresponds to the position of each character in the String. As mentioned above, different characters in Swift may require different amounts of memory to store, since the number of characters in Swift’s string is calculated based on Unicode scalars: a. A single scalar in a cluster, b. Scalable cluster of multiple scalars. So Swift strings cannot be indexed with integer values, and to determine where a particular character is located, we must traverse each Unicode scalar from the beginning or end of the string. Use the startIndex property to access the position of the first character of the string. The endIndex property is the position after the last character of the string. Therefore, the endIndex attribute is not a valid argument to a string subscript. If the string is empty, startIndex and endIndex are equal. Indexes before and after a given index can be accessed using the index(before:) and index(after:) methods of the string. To access an index far from a given index, you can use the index index(_:, offsetBy:) method instead of calling one of the methods multiple times. String title retrieves characters based on character Index: title[string.index (must be Index type)]

Let subStr = title[title.index(after: title.startindex)]//! O let subStr1 = title[title.index(before: title.endIndex)]//! < 🐪 let subStr2 = title[title.index(title.endIndex, offsetBy: -1)] //! < log:🐪 let subStr3 = title[title.index(title.startindex, offsetBy: 6)]//! < log: 🐨 let index = title.index(title.startIndex, offsetBy: 15) let subStr4 = title[index] //! < log: 🐌Copy the code

A runtime error is raised when attempting to access an index or character outside the range of the string.

/ /! Thread 1: Fatal error: String index is out of bounds let outsideIndex = title.index(after: The title endIndex) / /! Thread 1: Fatal error: String index is out of bounds let subStr5 = title[title.endIndex]Copy the code

Use the Indices attribute to get an index of all characters in a string.

let indices = title.indices; / /! DefaultIndices<String>(_elements: "Koala , Snail , Penguin , Dromedary ", _startIndex: Swift.String.Index(_rawBits: 0), _endIndex: Swift.String.Index(_rawBits: 3407872)) var tempStr:String = "" for index in indices { print("\(title[index])","",separator: "_", terminator: "", to: &tempStr) } ////! < final synthesis of the new string: K_o_a_l_a_ __ _ _S_n_a_i_l_ __, __ _P_e_n_g_u_i_n_ __, __ _D_r_o_m_e_d_a_r_y_ __ print (" final synthesis of the new string: \ (tempStr) ")Copy the code

Important: We can use the startIndex and endIndex attributes and the index index(before:) and index(after:) and index(_:, offsetBy:) methods on any type that conforms to the Collection protocol. This includes strings as well as collection types such as Array, Dictionary, and Set. String insertion and deletion: Insert: A single character is inserted at the index specified by the string using the insert(_:at:) method; Insert another string at the specified index using the INSERT (contentsOf:at) method.

var inserStr = "hello" //! Insert ("\u{1F1F7}", at: inserstr.startindex)//! < log: 🇷 hello / /! Insert single character: common character inserstr. insert("!" , at: inserStr.endIndex)//! < log: 🇷 hello! Insert with endIndex //! Let scalarStr = "\u{1F1F6}\u{1F496}"//! < 🇶💖 inserstr. insert(contentsOf: scalarStr, at: inserstr.startindex)//! The < 🇶 💖 🇷 hello! / /! NormalStr = "_word" insert. insert(contentsOf: normalStr, at: inserstr.index (before: inserStr.endIndex))//! The < 🇶 💖 🇷 hello_word!Copy the code

Delete: string removes a single character at the specified index using the remove(at:) method; Remove substrings in the specified range using the removeSubrange(_:) method:

Var removeStr = "\u{1F1F6}\u{1E67F}\u{1F496}\u{1F1F7}hello_word! eye\u{301}"//! < log: 🇶 💖 🇷 hello_word! Remove (at: removestr.index (removestr.startIndex, offsetBy: 2))//! < log: 🇶 🇷 hello_word! RemoveStr. Remove (at: removeStr. Index (removeStr. EndIndex, offsetBy: removeStr. - 2)) / /! < log: 🇶 🇷 hello_word! Ee / /! < delete substring in range 0-1: substring consisting of characters: Unicode scalars: 🇶 //*range // let range = removestr.startIndex.. < removestr.startIndex (removestr.startIndex, offsetBy: 2) // or let range = removestr.startIndex... removeStr.index(removeStr.startIndex, offsetBy: 1) removeStr.removeSubrange(range) //! The < 🇷 hello_word! eeCopy the code

Note: String type implements RangeReplaceableCollection agreement, other implements RangeReplaceableCollection agreement of any type can use the insert (_ : at:), Insert (contentsOf:at:), remove(at:) and removeSubrange(_:) methods. Examples are Array, Dictionary and Set. Substrings: When retrieving substrings from strings – for example, using indexes or methods like prefix(_:), the result is an instance of Substring instead of another string. Substrings in Swift have most of the same methods as strings, which means we can use substrings just like strings. But unlike strings, we only use substrings for a short time when performing operations on strings. When we need to store a substring for longer, we need to convert the substring to a String instance.

var myString = "\u{1F1F6}\u{1E67F}\u{1F496}\u{1F1F7}hello_word! eye\u{301}"//! < log: 𞙿 hello_word! //Return the last index where the specified value appears in the collection. Let subStart = myString.lastIndex(of:"🇷")?? myString.startIndex //! < character 🇷 position //Returns the first index where the specified value appears in the collection. let subEnd = myString.firstIndex(of: "_") ?? myString.endIndex//! Let subString = myString[subStart..<subEnd]//! < log: 🇷 hello print (subString) / / 3. Let longSubStr = String(subString) //! < or:String.init(subString)Copy the code

Key knowledge:

The difference between a string and a substring: Like a string, each substring has an area of memory for storing the characters that make up the substring. But as a performance optimization, a substring can reuse part of the memory used to store the original string, or part of the memory used to store another substring.Strings have similar optimizations, but two strings are equal if they share memoryThis performance optimization means that there is no performance cost of copying memory until the string or substring is modified. As mentioned above,Substrings are not good for long-term storage because they reuse the storage of the original string, and whenever any substrings are used, the entire original string must be kept in memory.

Example Description: myString is a string, which means it has an area of memory for storing the characters that make up the string. Because subString is a subString of myString, it reuses the memory used by myString. In contrast, longSubStr is a string that has its own storage when created from a substring.

String comparison: Comparison of whether strings and characters are equal: using the “equal” operators == and “not equal” operators! = Checks for string and character equality.

let testStr1 = "i have a cat\u{E9}?" / /! < I have a cate? let testStr2 = "i have a cat\u{65}\u{301}?" / /! < I have a cate? If testStr1 == testStr2 {print(" These two strings are equal ")}Copy the code

If an extended glyph cluster of two string values (or two character values) is equivalent in specification, they are considered equal. Extended glyphs clusters are equivalent in specification if they have the same language meaning and appearance, even if they are composed of different Unicode scalars. To take A counterexample: the capital letter A:\u{0041} in English is not the same as A:\u{0410} in Russian. Characters are visually identical but do not have the same linguistic meaning and are therefore not equal.

let englishA = "\u{0041}"//! < A let RussianA = "\u{0410}"//! < A if englishA == RussianA {print(" These two strings are equal ")} else {print(" these two strings are not equal ")//! < log: These two strings are not equal}Copy the code

Comparison of string prefixes and suffixes: To check whether a string has a particular string prefix or suffix, call the hasPrefix (_ 🙂 and hasSuffix (_ 🙂 methods of the string, both returning Boolean values.

let testStr1 = "i have a cat\u{E9}?" / /! < I have a cate? let testStr2 = "i have a cat\u{65}\u{301}?" / /! < I have a cate? let array = [testStr1,testStr2] for item in array[...] {if item.hasprefix (" I ") {print(item + "*")}} /* Note: the hasPrefix(_ :) and hasSuffix (_ :) methods perform a character-by-character canonical equivalence comparison between clusters of extended glglers in each string. */ for item in array[...]  { if item.hasSuffix("\u{E9}?" ) { print(item + "*")//! < output twice: I have a cate? *}}Copy the code

Note: Calling the hasPrefix (_ 🙂 and hasSuffix (_ 🙂 methods on each string does a canonical, character-by-character comparison of the Unicode representation of strings between extended glyph clusters of strings: When a Unicode string is written to a text file or other storage, the Unicode scalars in the string are encoded in one of the many Unicode defined encodings. Each encodings a string in units of code bits (binary bits). 1. Utf-8 encoding format: Encodes a string into eight bits of code. 2. Utf-16 encoding format: The string is encoded as multiple 16-bit codes. 3. Utf-32 encoding format: The string is encoded as 32 bits of code. Swift provides several ways to access Unicode for strings. A. Iterate over the string using a for-in statement, accessing its individual character values as a Unicode extended character cluster. B. Access string values according to one of the three Unicode-compatible encodings.

  • A collection of UTF-8 symbols, using stringsutf8Property access
  • A collection of UTF-16 symbols, using stringsutf16Property access
  • A 21-bit collection of Unicode scalar values, equivalent to the UTF-32 encoding of strings, using stringsunicodeScalarsProperty access.

1. Utf-8 representation: Access the UTF-8 encoding representation of a string by iterating through the UTF8 property of the string. The utF8 attribute is of type string.utf8View. UTF8View structure: The String contents are presented as a collection of UTF-8 symbols. We can access the UTF-8 symbol representation of a string using the string UTF8 attribute. UTF8View encodes Unicode scalar values of strings as unsigned 8-bit integers, so: String.UTF8View is a collection of unsigned 8-bit integer UInt8 values. Unicode scalar values in a string can be up to 21 bits. Multiple UNITS of UTF-8 code are typically required to represent these scalar values using 8-bit integers.

Utf8 {print(v,"",separator: "", terminator: ")// replace newline} //! < the console output: 70, 108, 111, 119, 101, 114, 115, 32, 240, 159, 146, 144 / * is a 💐 characters unicode scalar: \ u f490 {1} flowermoji unicodeScalars: The 32-bit 0001F490 character is \u{1F490} and the printed value is: 128144 * / let flowermoji = "💐" let flowermojiUnicodeScalars = flowermoji. UnicodeScalars / /! For v in flowermojiUnicodeScalars {print(v,v.value)//! < v.value = 128144 9*16 + 4*256 +15 *256 *16 + 256 *256 = 128144} Var count = 0 var value = "" for v in flowermoji.utf8 {count += 1 value += "\(v) "} Console. log: 💐 Print ("\u{1F490} "print("\u{1F490}" print("\u{1F490} ")Copy the code

Such asLet dogString = "Dog ‼ 🐶"conversionUTF-8A collection of"68 111 103 226 128 188 240 159 144 182"

2. Utf-16 representation: Access the UTF-16 representation of a string by iterating over the UTF16 attribute of the string. The utf16 property is of type String.utf16View, the same as string.utf8View. Difference: String.UTF16View is a collection of unsigned 16-bit integer UInt16 values. Unicode scalar values in a string can be up to 21 bits. To represent these scalar values as 16-bit integers, you might need two UTF-16 code units.

Let dogString = "Dog ‼ 🐶" var count = 0 var value = "" for v in dogstring. utf16 {count += 1 value += "\(v) "} 🐶 Unicode scalar conversion to utF16 set: 68 111 103 8252 55357 56374 print("\u{1F436}unicode scalar conversion to utF16 set: \ "(value)) / / 🐶 : \ u f436 {1}Copy the code

3.Unicode Scalar representation: Access the Unicode Scalar representation (set) of a string by iterating over the unicodeScalars property of the string. UnicodeScalars property is of type string. UnicodeScalarView. Each UnicodeScalar has a value property: an instance object of Unicod. Scalar, which uses an unsigned 32-bit integer UInt32 and returns the value of a Scalar.

for scalar in dogString.unicodeScalars {
    print("\(scalar.value) ", terminator: "")// log "68 111 103 8252 128054 "
}
Copy the code

Resources: Swift 5.1 official programming guide


Recommended articles:

5 minutes. Markdown syntax Swift 5.1(2) – Operator Swift 5.1(1) – Basic iOS UI state save and restore (3) iOS UI state save and restore (2) iOS UI state save and restore (1) iOS accurate timing common methods Sign In With Apple