Swift-字符串的處理

1、字符串的聲明swift

        //聲明一個空字符串
        let emptystring = ""
        //定義變量類型爲String
        let str: String = "Hello Word!"
        //未定義變量類型,在swift中會根據值推測變量的類型爲String
        let str1 = "Hello World"    

2、判斷字符串是否爲空數組

        //判斷字符串是否爲空,若爲空則爲true,不然爲false
        let isEmpty : Bool = str.isEmpty
        print("emptystring = \(emptystring) str = \(str) str1 = \(str1) isEmpty = \(isEmpty)")
        //判斷字符串是否爲空,在定義變量類型時容許變量爲空,則能夠使用 xx == nil 的方式來判斷
        var str2: String?
        if str2 == nil {
            print("str2 爲空")
        } else {
            print("str2 不爲空")
        }    

3、字符串的截取spa

         let str = "Hello World"
//        str = str + " " + str
        //一、遍歷字符串的全部字符
        for c in str {
            print("ns1 = \(c)");
        }
        //二、字符串的長度
        let stringLength = str.count
        print("字符串的長度 = \(stringLength)")
        
        //三、截取方法
        //        1)從某個位置開始截取
        let indexStartOfText = str.index(str.startIndex, offsetBy: 3)
        let substring1 = str[indexStartOfText...]
        print("substring1 = \(substring1)")
//        2)截取到某個位置
        let indexEndOfText = str.index(str.endIndex, offsetBy: -2)
        let subSting2 = str[...indexEndOfText]
        print("subString2 = \(subSting2)")
        
//        3)從某個位置截取到某個位置
        let indexStart = str.index(str.startIndex, offsetBy: 3)
        let indexEnd = str.index(str.endIndex, offsetBy: -4)
        let subSting3 = str[indexStart..<indexEnd]
        print("subString3 = \(subSting3)")
        
        //在最後把截取獲得的字符串須要轉換回String
        let subString4 = String(subSting2)
        print("subString4 = \(subString4)")
        
        
//        另外一種截取方式
//        截取到某個位置
        let indexStartNew = str.index(str.endIndex, offsetBy: -3)
        let subString5 = str.prefix(through: indexStartNew)
        print("subString5 = \(String(subString5))")
        
        let sufixString = str.prefix(upTo: indexStartNew)
        print("sufixString = \(sufixString)")
        
//        從某個位置開始截取
        let subString6 = str.suffix(from: indexStartNew)
        print("subString6 = \(String(subString6))")    

4、字符串的拼接code

         //字符串的鏈接主要有兩種方式: 一種是直接在字符串後面添加字符串,另外一種是將字符串數組拼接成一個字符串
//        方式一
        let str = "Hello"
        let str2 = "world"
        let str3 = str + str2//利用+直接將字符串拼接在一塊兒,比較直接
        print("str3 = \(str3)")
//        方式二
        let array11: [String] = ["aaa","bbb", "ccc"]
        //將數組中的元素拼接成字符串
        let arrayStr : String! = array11.joined(separator: ",")
         print("arrayStr = \(arrayStr!)")    
相關文章
相關標籤/搜索