String的用法总结-swift

学习swift的String用法总结

  学习了swift的String的用法之后感觉比OC的太直接了,不需要直接的初始化、类型声明也不用区分可变和不可变的类型,基本上就是属于哪里需要就在哪里直接写就可以的状态。

 

 

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        print("viewDidLoad")
        
        //字符串
        //初始化空字符串
        let emptyString = ""               // 空字符串字面量
        let anotherEmptyString = String()  // 初始化方法
        // 两个字符串均为空并等价。
        if emptyString.isEmpty && anotherEmptyString.isEmpty {
            print("Nothing to see here")
        }
        // 打印输出:"Nothing to see here"
        
        
        //字符串可以通过传递一个值类型为Character的数组作为自变量来初始化
        let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
        let catString = String(catCharacters)
        print(catString)// 打印输出:"Cat!🐱"
        
        
        //数值型字符串转化为数值
        let numberOfStr = "123.6"
        let convertedNumber = Double(numberOfStr)//将数值型字符串 转化为数值
        print("stringValue:'\(numberOfStr)\' convertedNumberValue:\(convertedNumber!)")//打印 stringValue:'123.6' convertedNumberValue:123.6
        
        
        //字符串的遍历
        let randomString = "hello everybody"
        for char in randomString.characters{
        
            print("The results of the ergodic:\(char)")
            /*打印
             The results of the ergodic:h
             The results of the ergodic:e
             The results of the ergodic:l
             The results of the ergodic:l
             The results of the ergodic:o
             The results of the ergodic:
             The results of the ergodic:e
             The results of the ergodic:v
             The results of the ergodic:e
             The results of the ergodic:r
             The results of the ergodic:y
             The results of the ergodic:b
             The results of the ergodic:o
             The results of the ergodic:d
             The results of the ergodic:y*/
        }
        
        
        //字符串拼接
        let str1 = "hello "
        let str2 = "word"
        var str = ""
        str = str1 + str2//字符串拼接
        print("The joining together of two strings:\(str)")//打印 The joining together of two strings:hello word

        
        let exclamationMark:Character = "!"
        str.append(exclamationMark)//将一个字符串添加到另一个字符串的尾部
        print("使用append拼接一个字符:\(str)")//打印 使用append拼接一个字符:hello word!
        
        let subStr = "word"
        str.append(subStr)
        print("使用append拼接一个子字符串:\(str)")//打印 使用append拼接一个子字符串:hello word!word
        
        
        //字符串插值
        let addend = 6
        let sumStr = "\(addend) add 8.1 is \(Double(addend) + 8.1)"
        print(sumStr)//打印 6 add 8.1 is 14.1
        
        
        //字符串字面量的特殊字符
        let dollarSign = "\u{24}"             // $, Unicode 标量 U+0024
        let blackHeart = "\u{2665}"           // ♥, Unicode 标量 U+2665
        let sparklingHeart = "\u{1F496}"      // 💖, Unicode 标量 U+1F496
        
        print(dollarSign,blackHeart,sparklingHeart)//打印 $ ♥ 💖
        
        //可扩展的字形群集
        let eAcute: Character = "\u{E9}"                         // é
        let combinedEAcute: Character = "\u{65}\u{301}"          // e 后面加上  ́
        // eAcute 是 é, combinedEAcute 是 é
        print("eAcuteValue:\(eAcute),combinedEAcuteValue:\(combinedEAcute)")//打印 eAcuteValue:é,combinedEAcuteValue:é
        
        //字符串的索引
        //可扩展的字符群集可以组成一个或者多个 Unicode 标量。这意味着不同的字符以及相同字符的不同表示方式可能需要不同数量的内存空间来存储。所以 Swift 中的字符在一个字符串中并不一定占用相同的内存空间数量。因此在没有获取字符串的可扩展的字符群的范围时候,就不能计算出字符串的字符数量。如果您正在处理一个长字符串,需要注意characters属性必须遍历全部的 Unicode 标量,来确定字符串的字符数量。
        //另外需要注意的是通过characters属性返回的字符数量并不总是与包含相同字符的NSString的length属性相同。NSString的length属性是利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展的字符群集。
        //前面提到,不同的字符可能会占用不同数量的内存空间,所以要知道Character的确定位置,就必须从String开头遍历每一个 Unicode 标量直到结尾。因此,Swift 的字符串不能用整数(integer)做索引。
        //使用startIndex属性可以获取一个String的第一个Character的索引。使用endIndex属性可以获取最后一个Character的后一个位置的索引。因此,endIndex属性不能作为一个字符串的有效下标。如果String是空串,startIndex和endIndex是相等的。
        //通过调用 String 的 index(before:) 或 index(after:) 方法,可以立即得到前面或后面的一个索引。您还可以通过调用 index(_:offsetBy:) 方法来获取对应偏移量的索引,这种方式可以避免多次调用 index(before:) 或 index(after:) 方法。
        
        let stringIndexStr = "hello word!"
        let starIndexC = stringIndexStr[stringIndexStr.startIndex]//获取字符串第一个索引的 字符
        print("startIndexValue:\(stringIndexStr.startIndex)")//打印 startIndexValue:Index(_base: Swift.String.UnicodeScalarView.Index(_position: 0), _countUTF16: 1)
        
        print("starIndexCharacter:\(starIndexC)")//打印 starIndexCharacter:h
        
        //endIndex属性不能作为一个字符串的有效下标,运行时会崩溃
        //let endIndexC = stringIndexStr[stringIndexStr.endIndex]//试图获取越界索引对应的 Character,将引发一个运行时错误。
        //print("endIndexCharacter:\(endIndexC)")
        
        
        let afterIndexC = stringIndexStr[stringIndexStr.index(after: stringIndexStr.startIndex)]//获取字符串 第二个索引的字符(第一个索引后面的一个索引值)
        print(afterIndexC)//打印 e
        
        
        let beforeIndexC = stringIndexStr[stringIndexStr.index(before: stringIndexStr.endIndex)]//获取字符串末尾的一个字符(最后一个索引前面的一个索引,使用endIndex属性可以获取最后一个Character的后一个位置的索引,endIndex属性不能作为一个字符串的有效下标)
        print(beforeIndexC)//打印 !
        
        
        
        let offSetByIndex = stringIndexStr.index(stringIndexStr.startIndex, offsetBy: 4)//第一个索引4个偏移量之后的一个索引
        print(offSetByIndex,stringIndexStr[offSetByIndex])//打印 Index(_base: Swift.String.UnicodeScalarView.Index(_position: 4), _countUTF16: 1) o
        
        
        
        //字符串的插入和删除
        
        //字符串插入
        var welcome = "hello"
        welcome.insert("!", at: welcome.endIndex)//插入一个字符
        print("insertNewCharacters:\(welcome)\n");//打印 insertNewCharacters:hello!
        
        
        
        welcome.insert(contentsOf: " word".characters, at: welcome.index(before: welcome.endIndex))//插入一个子字符串
        print("insertNewSubStr:\(welcome)\n")//打印 insertNewSubStr:hello word!
        
        
        //字符串删除
        welcome.remove(at: welcome.index(before: welcome.endIndex))//删除最后一个字符
        print("removeStrLastCharacters:\(welcome)\n")//打印 removeStrLastCharacters:hello word
        
        
        let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
        welcome.removeSubrange(range)//删除规定范围内的子串
        print("removeStrRange:\(welcome)\n")//打印 removeStrRange:hell
        
       //字符串的比较(Swift 提供了三种方式来比较文本值:字符串字符相等、前缀相等和后缀相等。)
        let quotation = "We're a lot alike, you and I."
        let sameQuotation = "We're a lot alike, you and I."
        if quotation == sameQuotation {//如果两个字符串(或者两个字符)的可扩展的字形群集是标准相等的,那就认为它们是相等的。在这个情况下,即使可扩展的字形群集是有不同的 Unicode 标量构成的,只要它们有同样的语言意义和外观,就认为它们标准相等。(例如,LATIN SMALL LETTER E WITH ACUTE(U+00E9)就是标准相等于LATIN SMALL LETTER E(U+0065)后面加上COMBINING ACUTE ACCENT(U+0301)。这两个字符群集都是表示字符é的有效方式,所以它们被认为是标准相等的:)
            
            print("These two strings are considered equal")
            
        }
        // 打印输出 "These two strings are considered equal"
        
        
        //相反,英语中的LATIN CAPITAL LETTER A(U+0041,或者A)不等于俄语中的CYRILLIC CAPITAL LETTER A(U+0410,或者A)。两个字符看着是一样的,但却有不同的语言意义:
        
        let latinCapitalLetterA: Character = "\u{41}"
        
        let cyrillicCapitalLetterA: Character = "\u{0410}"
        
        if latinCapitalLetterA != cyrillicCapitalLetterA {
            
            print("These two characters are not equivalent")
        }
        // 打印 "These two characters are not equivalent"
        
        
        //前缀/后缀相等
        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(_:)方法来计算话剧中第一幕的场景数:(遍历查找前缀相等)
        var act1SceneCount = 0
        for scene in romeoAndJuliet {
            
            if scene.hasPrefix("Act 1 ") {
                
                act1SceneCount += 1
            }
        }
        
        print("There are \(act1SceneCount) scenes in Act 1")
        // 打印输出 "There are 5 scenes in Act 1"
        
        
        //可以用hasSuffix(_:)方法来计算发生在不同地方的场景数:(后缀相等)
        var mansionCount = 0
        var cellCount = 0
        for scene in romeoAndJuliet {
            if scene.hasSuffix("Capulet's mansion") {
                mansionCount += 1
            } else if scene.hasSuffix("Friar Lawrence's cell") {
                cellCount += 1
            }
        }
        print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
        // 打印输出 "6 mansion scenes; 2 cell scenes"
    
        //hasPrefix(_:)和hasSuffix(_:)方法都是在每个字符串中逐字符比较其可扩展的字符群集是否标准相等
}

 

posted @ 2017-06-02 12:00  #零下一度&  阅读(5858)  评论(0编辑  收藏  举报