Swift learns the second shot

Source: Internet
Author: User
Tags scalar

The last time you learned about variable constants, data types, and conversions between data types, this time start with a string.

1. String literal (string literals)

You can include a predefined string value in your code as a string literal. String literals are wrapped in double quotation marks ("") with a fixed-order text character set. String literals can be used to provide initial values for constants and variables:

let"Some string literal value"

Note that somestring constants are initialized by string literals, and Swift infers that the constant is of type string.
Note:
Initialize the empty string (Initializing an empty string), to create an empty string as the initial value, you can assign an empty string literal to a variable, or you can initialize a new string instance:

var""// 空字符串字面量varString// 初始化方法// 两个字符串均为空并等价。Boolean 类型的 isEmpty 属性来判断该字符串是否为空:if emptyString.isEmpty {print("Nothing to see here")}// 打印输出:"Nothing to see here"
2. String variability (String mutability)

You can modify a specific string by assigning it to a variable, or assign it to a constant to ensure it is not modified:

var"Horse"" and carriage"// variableString 现在为 "Horse and carriage"let"Highlander"" and another Highlander"// 这会报告一个编译错误 (compile-time error) - 常量字符串不可以被修改。

Note:
In Objective-c and Cocoa, you need to specify whether a string can be modified by selecting two different classes (NSString and nsmutablestring).

3. String is a value type (Strings is value Types)

Swift's String type is a value type. If you create a new string, the value is copied when it is used for constants, variable assignment operations, or when passed in a function/method. In any case, a new copy of the existing string value is created and the new copy is passed or assigned.
Note:
Unlike nsstring in Cocoa, when you create a NSString instance in Cocoa and pass it to a function/method, or assign a value to a variable, you pass or assign a reference to the NSString instance unless you specifically require a value copy, Otherwise, the string does not generate a new copy for the assignment operation.
The Swift default string copy ensures that the value of the string is passed in the function/method. It's obvious that wherever that value comes from, it's all on your own. You can be sure that the passed string will not be modified unless you modify it yourself.
At actual compile time, the Swift compiler optimizes the use of strings so that actual replication occurs only when absolutely necessary, which means that you can achieve very high performance when you use strings as value types.

4. Using characters (working with characters)

You can use the for-in loop to iterate through the characters property in a string to get the value of each character:

forcharacterin"Dog!?".characters {print(character)}// D// o// g// !// ?

The for-in loop is described in detail in for Loops (p. 0).
In addition, you can create a separate character constant or variable by marking a Character type and assigning it with a character literal:

let"!"

A string can be initialized by passing an array of value type Character as an argument:

let catCharacters: [Character] = ["C""a""t""!""?"]letString(catCharacters)print(catString)// 打印输出:"Cat!?"
5. Connection strings and characters (concatenating Strings and characters)

A string can be added together (or "concatenated") by adding an operator (+) to create a new string:

let"hello"let" there"var welcome = string1 + string2// welcome 现在等于 "hello there"

You can also add a string to an already existing string variable with the addition assignment operator (+ =):

var instruction = "look over"instruction += string2// instruction 现在等于 "look over there"

You can append a character to the end of a string variable using the Append () method:

let exclamationMark: Character = "!"welcome.append(exclamationMark)// welcome 现在等于 "hello there!"

Attention:

You cannot add a string or character to a character variable that already exists because the character variable can contain only one character.

6. String interpolation (string interpolation)

String interpolation is a way to construct a new string that can contain constants, variables, literals, and expressions. The string literal that you inserted
are in parentheses prefixed with a backslash:

let multiplier = 3let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"// message is "3 times 2.5 is 7.5"

In the example above, multiplier as (multiplier) is inserted into a string constant amount. When a string is created to perform an interpolation calculation, this placeholder is replaced with the actual value of multiplier. The value of multiplier also acts as part of the subsequent expression in the string. The expression evaluates the value of Double (multiplier) * 2.5 and inserts the result (7.5) into the string. In this example, the expression is written as (Double (multiplier) * 2.5) and is included in the string literal.

Note:
Expressions written in parentheses in an interpolated string cannot contain non-escaped double quotation marks (") and backslashes (\), and cannot contain carriage returns or newline characters.

7.Unicode

Unicode is an international standard for encoding and representation of text. It enables you to represent almost all characters from any language in a standard format and to read and write to characters in external resources such as text files or Web pages. Swift's String and Character types are complete
Fully compatible with the Unicode standard.

7.1Unicode scalar (Unicode scalars)

Swift's String type is based on Unicode scalars. A Unicode scalar is a unique 21-digit number that corresponds to a character or modifier, such as u+0061 for the lowercase Latin alphabet (LATIN SMALL letter A) ("a"), and u+1f425 for the chicken table (fron
T-facing BABY chick) ("?").

* * Note: The **unicode code bit (code poing) ranges from u+0000 to u+d7ff or u+e000 to U+10FFFF. Unicode
Scalars do not include Unicode surrogate (surrogate pair) code bits, whose code-bit range is u+d800 to U+DFFF.
Note that not all 21-bit Unicode scalars represent one character, because some scalars are reserved for future allocations. Already represents a typical character
Scalars have their own names, such as LATIN SMALL letter A and front-facing BABY chick in the example above.
string literal special character (special characters in string literals)

* * String literals can contain the following special characters:
? Escape character \ (null character), \ (backslash), \ t (horizontal tab), \ n (line break), \ r (carriage return), \ "(double quotation mark), \ ' (single-cited
Number). **

? Unicode scalar, written as \u{n} (U is lowercase), where n is any one to eight hexadecimal digits and the available Unicode bit codes.
The following code is an example of the use of various special characters. The Wisewords constant contains two double quotes. Dollarsign, Blackheart and S
The Parklingheart constant demonstrates three Unicode scalars in different formats:

let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"// "Imageination is more important than knowledge" - Enisteinlet dollarSign = "\u{24}" // $, Unicode 标量 U+0024let blackHeart = "\u{2665}" // ?, Unicode 标量 U+2665let sparklingHeart = "\u{1F496}" // ?, Unicode 标量 U+1F496
8. Calculate the number of characters (counting characters)

If you want to get the number of Character values in a string, you can use the Count property of the characters property of the string:

let unusualMenagerie = "Koala ?, Snail ?, Penguin ?, Dromedary ?"print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")// 打印输出 "unusualMenagerie has 40 characters"

Note In Swift, when you use the extensible character clouds set as the Character value to concatenate or change a string, it does not necessarily change the character of the string
The number of characters.

For example, if you use the four-character word cafe to initialize a new string, then add a combining Actue Accen
T (u+0301) as the end of the string. Eventually the number of characters in this string is still 4, because the fourth character is E, not e:

var word = "cafe"print("the number of characters in \(word) is \(word.characters.count)")// 打印输出 "the number of characters in cafe is 4"word += "\u{301}" // COMBINING ACUTE ACCENT, U+0301print("the number of characters in \(word) is \(word.characters.count)")// 打印输出 "the number of characters in café is 4"

Attention:
An extensible set of character clouds can form one or more Unicode scalars. This means that different characters and different representations of the same characters can be
Can require a different amount of memory space to store. Therefore, the characters in Swift do not necessarily occupy the same amount of memory space in a string. Because
It is not possible to calculate the number of characters in a string when there is no scope to get the extensible character clouds of the string. If you are working with a long word
Note that the characters property must traverse all Unicode scalars to determine the number of characters in the string.
It is also important to note that the number of characters returned by the characters property is not always the length property of the nsstring containing the same character
Same. The length property of NSString is the 16-bit code unit number represented by UTF-16, not the Unicode extensible character
Cluster. As a support, when a NSString's length property is accessed by a swift String value, it is actually called Utf16cou
Nt.

9 Accessing and modifying strings (accessing and modifying a string)

You can access and read it by using the properties and methods of the string, or you can do it with the following banner.

9.1 String Index (Indices)

Each string value has an associated index (index) type String.index, which corresponds to the position of each Character in the string.
As mentioned earlier, different characters may occupy a different amount of memory space, so to know the location of Character, you must traverse each Unicode scalar from the beginning of a string to the end. Therefore, Swift's string cannot be indexed with integers (integer).

Use the StartIndex property to get the index of the first Character of a String. You can use the EndIndex property to get the index of the last position of a character. Therefore, the EndIndex property cannot be used as a valid subscript for a string. If the string is an empty string, StartIndex and EndIndex are equal.

By calling String.index's predecessor () method, you can immediately get to the previous index, and the call to the successor () method immediately gives you a later index. The index of any String can be used to obtain another index by means of the chain action, or it can call Advancedby (_:). method to obtain the. However, if you try to get an out-of-bounds string index, a run-time error is thrown.

You can use the subscript syntax to access the Character of a String-specific index.

let greeting = "Guten Tag!"greeting[greeting.startIndex]// Ggreeting[greeting.endIndex.predecessor()]// !greeting[greeting.startIndex.successor()]// ulet index = greeting.startIndex.advancedBy(7)greeting[index]// a

Attempting to obtain a Character corresponding to an out-of-bounds index throws a run-time error.

greeting[greeting.endIndex] // errorgreeting.endIndex.successor() // error

Using the indices property of the characters property creates a range (range) that contains the full index, which is used to access a single character in a string.

for index in greeting.characters.indices {print("\(greeting[index]) ", terminator: "")}// 打印输出 "G u t e n T a g !"
9.2 Insert and delete (Inserting and removing)

Call Insert (_:atindex:) method to insert a character at the specified index of a string.

var welcome = "hello"welcome.insert("!", atIndex: welcome.endIndex)// welcome now 现在等于 "hello!"

Call Insertcontentsof (_:at:) method to insert a string at the specified index of a string.

welcome.insertContentsOf(" there".characters, at: welcome.endIndex.predecessor())// welcome 现在等于 "hello there!"

Call Removeatindex (_:) method to delete a character at the specified index of a string.

welcome.removeAtIndex(welcome.endIndex.predecessor())// welcome 现在等于 "hello there"

Call RemoveRange (_:) method to delete a substring at the specified index of a string.

let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndexwelcome.removeRange(range)// welcome 现在等于 "hello"
10 comparison string (comparing Strings)

Swift provides three ways to compare text values: String characters typeface, prefixes equal, and suffixes equal.

10.1 Strings/characters typeface (string and Character equality)

The string/character can be used equal to operator (= =) and not equal to operator (! =)

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")}// 打印输出 "These two strings are considered equal"
10.2 prefix/suffix equal (Prefix and Suffix Equality)

By calling the string Hasprefix (:)/hassuffix (:) method to check whether a string has a specific prefix/suffix, and two methods receive a
A String parameter, and returns a Boolean value.

The following example shows the position of the first two scenes of the Shakespeare play Romeo and Juliet in a string 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 call Hasprefix (_:) method to calculate the number of scenes in the first act of a play:

var act1SceneCount = 0for scene in romeoAndJuliet {if scene.hasPrefix("Act 1 ") {++act1SceneCount}}print("There are \(act1SceneCount) scenes in Act 1")// 打印输出 "There are 5 scenes in Act 1"

Similarly, you can use Hassuffix (_:) method to calculate the number of scenes that occur in different places:

var mansionCount = 0var cellCount = 0for scene in romeoAndJuliet {if scene.hasSuffix("Capulet‘s mansion") {++mansionCount} else if scene.hasSuffix("Friar Lawrence‘s cell") {++cellCount}}print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")// 打印输出 "6 mansion scenes; 2 cell scenes

The string is basically about these operations.

Here is one of my Learning swift open source libraries.

Swift learns the second shot

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.