美文网首页Swift
Swift 3.0之三、字符串和字符

Swift 3.0之三、字符串和字符

作者: 麟young | 来源:发表于2016-12-02 17:14 被阅读10次

    1. 字符串字面量

    let someString = "Some string literal value"
    // someString 常量被推断类型为 String
    

    2. 空字符串的初始化

    两种方式,举个栗子🌰 :

    var emptyString = ""               // 方式一 
    var anotherEmptyString = String()  // 方式二
    // 两种方式都初始化为一个空字符串,即 “”。
    

    通过检查字符串常量或变量的isEmpty属性来确认一个String值是否为空:

    if emptyString.isEmpty {
        print("Nothing to see here")
    }
    // 结果为: "Nothing to see here"
    

    3. 字符串可变性

    String常量不可修改值;
    String变量 可以修改值。

    4. 字符串是值类型

    值类型意味着,每一次赋值,拿到的都是String对象的拷贝,而非对象本身。 (浅拷贝)

    5. 字符类型 (Character)

    • 用字符串字面量初始化一个Character类型的变量:
    let exclamationMark: Character = "!"
    
    • for...in语句遍历String类型对象,打印所有字符,举个🌰 :
    for character in "Dog!?".characters {
        print(character)
    }
    // D
    // o
    // g
    // !
    // ?
    
    • 用字符数组初始化一个字符串:
    let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"] // 初始化一个字符数组
    let catString = String(catCharacters)                       // 将数组转化为字符串
    print(catString)                                            // 结果为: "Cat!🐱"
    

    6. 连接字符串或字符

    举个🌰 :

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

    上面的🌰 也可以简写为下面的 🌰 :

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

    字符串后追加字符, 使用append(_)函数:

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

    7. 字符串插值

    一个反斜杠 \ 加上一枚小括号() 等于 \(), 举个🌰 :

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

    8. 字符串的字符统计

    let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪 "
    print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
    // 'unusualMenagerie.characters' 为字符串的字符数组,然后取其count值,即此字符串的字符数量。
    // 结果为: "unusualMenagerie has 40 characters"
    

    9. 访问和修改字符串

    字符串索引

    每一个String值都有索引类型,String.Index,它相当于每个Character在字符串中的位置。使用startIndex属性来访问String中第一个Character的位置:

    let greeting = "Guten Tag!"
    greeting[greeting.startIndex]  // G
    

    endIndex属性是 String中最后一个字符再往后一位的位置。因此,endIndex属性并不是字符串下标脚本的合法实际参数。如果String为空,则 startIndexendIndex相等。

    使用 index(before:)index(after:) 方法来访问给定索引的前或后一个位置:

    greeting[greeting.index(before: greeting.endIndex)]
    // !
    greeting[greeting.index(after: greeting.startIndex)]
    // u
    

    使用index(_:offsetBy:)方法访问偏离第一个参数某个长度的位置:

    let index = greeting.index(greeting.startIndex, offsetBy: 7)
    greeting[index]
    // a
    

    尝试访问索引位置在字符串范围之外,就会触发运行时错误:

    greeting[greeting.endIndex]     // error
    greeting.index(after: endIndex) // error
    

    字符串characters属性是一个字符数组,数组的indices(index的复数形式)属性,代表字符串的索引数组:

    for index in greeting.characters.indices {
        print("\(greeting[index]) ", terminator: " ")
    }
    // 结果为: "G u t e n   T a g ! "
    

    插入和删除

    插入字符,使用insert(_:at:)方法,
    插入字符串,使用insert(contentsOf:at:)方法:

    var welcome = "hello"
    welcome.insert("!", at: welcome.endIndex)
    // welcome 现在为 "hello!"
     
    welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex))
    // welcome 现在为 "hello there!"
    

    移除某个位置字符,使用remove(at:)方法,
    移除某段位置字符,使用removeSubrange(_:)方法:

    welcome.remove(at: welcome.index(before: welcome.endIndex))
    // welcome 现在为 "hello there"
     
    let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
    welcome.removeSubrange(range)
    // welcome 现在为 "hello"
    

    任何遵循RangeReplaceableIndexable协议的类型都可使用insert(_:at:)insert(contentsOf:at:)remove(at:)方法,包括 String类型,还有集合类型如 : ArrayDictionarySet

    10. 字符串比较

    字符串和字符相等性

    字符串比较使用“等于”运算符 (==) 和“不等”运算符 (!=)进行检查:

    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"
    

    前缀和后缀相等性

    要检查一个字符串是否拥有特定的字符串前缀或者后缀,调用字符串的hasPrefix(_:)hasSuffix(_:)方法,返回一个布尔值。举个罗密欧与朱丽叶的🌰 :

    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"
    ]
    // 初始化数组
    

    使用hasPrefix(_:)方法计算数组中前缀为"Act 1"的数量:

    var act1SceneCount = 0
    for scene in romeoAndJuliet {
        if scene.hasPrefix("Act 1 ") {
            ++act1SceneCount
        }
    }
    print("There are \(act1SceneCount) scenes in Act 1")
    // 结果为: "There are 5 scenes in Act 1"
    

    使用hasSuffix(_:)方法计算数组中后缀为"Capulet’s mansion"和"Friar 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
        }
    }
    print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
    // 结果为: "6 mansion scenes; 2 cell scenes"
    

    相关文章

      网友评论

        本文标题:Swift 3.0之三、字符串和字符

        本文链接:https://www.haomeiwen.com/subject/lvhqmttx.html