Swift Learning Swift Programming Tour---characters and strings (v)

Source: Internet
Author: User



String is the string type of Swift. A string is a valid sequence of characters, so you can also make a character set fit. A string can be concatenated with the + symbol. The string type is a fast, modern string implementation. Each string consists of independently encoded Unicode characters and provides support for accessing these characters in different Unicode representations. Use "" to mark the string.



  First, initialize the empty string  


 
var emptyString = ""    
var anotherEmptyString = String()





These 2 types of initialization methods are equivalent.



IsEmpty can determine whether the current string is an empty string.


 
if emptyString.isEmpty {
    print("Nothing to see here")
}





Swift's String type is a value type. If you create a new string value, the value is copied when it is passed in a constant, variable assignment operation, or in a function/method. In different cases, a new copy of the existing string value is created, and the new copy is passed or assigned.






  Second, the use of characters (characters)



  You can access the string's individual characters through the for-in loop.


 
for character in "Dog!??".characters {
    print(character)
}




In addition, you can create an independent character constant or variable by marking a Character type annotation and assigning it by character literal:


String values can be constructed using the passing of a character array.


 
let catCharacters: [Character] = ["C", "a", "t", "!", "??"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!??  





  Third, connection strings and characters



String values can be used to create a new string value by using the + symbol to implement a string connection.


 
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there





You can also append a string value to an existing string variable using the assignment operator (+ =)


 
var instruction = "look over"
instruction += string2
// instruction now equals "look over there





Use the Append () method to speak a character value after attaching to a string value.


 
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!





You cannot append a string or character to an existing character variable, because the character value must contain a single character






  Four, string interpolation



String interpolation is a new way to build a string that contains constants, variables, literals, and expressions. Each entry of the string literal that you insert is wrapped in parentheses prefixed with 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




In the example above, multiplier as \ (multiplier) is inserted into a string literal. When you create a string to perform an interpolation calculation, this placeholder is replaced with the multiplier actual value. 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 your interpolated string cannot contain non-escaped double quotation marks (") and backslashes (\), and cannot contain carriage returns or line feeds.






Five, character Count



We can use the Count property of the characters property of string to get the character count of the strings, which is the length of the string. See the example below









Output









Note the use of Swift's eigenvalues extended glyph cluster means that string connections and modifications may not affect the number of characters in a string






Output









  Vi. Accessing and modifying strings (accessing and modifying a string)






We access and modify strings through the methods and properties of string, or by using the following banner.






1. String index



Each string value is associated with an index type, String.index, the index corresponds to the position of each character in the string, and different roles require a different amount of memory to store, so in order to determine which characters are in a particular position, you must traverse each Unicode scalar from the beginning or end of the string. For this reason, Swift's string cannot be indexed with an integer value.



Use the StartIndex property to access the position of the first character of the string, use the Endindex property to access the position after the last character, and as a result, the Endindex property is not a valid string subscript parameter.



If a string is empty, then startIndex and endIndex are equal.



  The string.index value can use the successor () method to access its next character. An attempt to access an index outside the range of a string will trigger a run-time error. Use the predecessor () method to access the previous character of a string



Here's an example to illustrate these methods






Output results






When we try to write code like this,



Print (Greeting[greeting.startindex.predecessor ())) access the previous character of the starting position



Print (Greeting[greeting.endindex.successor ()]) accesses the next character at the end position



A run-time error will occur









Use the indices property of the characters property to create a range of all indexes












  2. Insert and Delete (Inserting and removing)



Use Insert (_:atindex:) to insert a character into a string at the specified position


 
var welcome = "hello"
welcome.insert("!", atIndex: welcome.endIndex)
// welcome now equals "hello!


Inserts a string into a string at the specified position using insertcontentsof (_:at:)


 
welcome.insertContentsOf(" there".characters, at: welcome.endIndex.predecessor())
// welcome now equals "hello there!





Use Removeatindex (_:) to remove a character from a string at a specified location


 
welcome.removeAtIndex(welcome.endIndex.predecessor())
// welcome now equals "hello there





Use RemoveRange (_:) to delete a substring at a specified position in a string


 
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
welcome.removeRange(range)
// welcome now equals "hello"





Seven, comparing strings


Swift provides three ways to compare the values of strings: strings are equal, prefixes are equal, and suffixes are equal. 1. string EqualityIf two strings contain exactly the same characters in the same order, the strings are 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"





2. prefix/suffix equal


Checks whether a string has a specific prefix/suffix by calling the Hasprefix/hassuffix method of the string. All two methods need to pass in a string as a parameter and return a Boolean value. Two methods perform a character-by-byte comparison between the base string and the prefix/suffix string. The following example shows the position of the first two scenes of Shakespeare's 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" 
] 


Use the Hasprefix method to calculate the number of scenes in the first scene of a play using the Romeoandjuliet array:


 
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" 





Similarly, the Hassuffix method can be used to calculate the number of scenes that occur in and around Capulet mansions and Lawrence cells.


 
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" 





3. Uppercase and lowercase strings



Gets the uppercase/lowercase version of a string by using the Uppercasestring and LowerCaseString properties of the string.


let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty value is "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered value is "could you help me, please?" 





Swift Learning Swift Programming Tour---characters and strings (v)


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.