Swift String常用方法_Swift基礎

來源:互聯網
上載者:User

       參考Java String類, 對Swift String用法做個總結。

基礎篇:

1、 字串長度: 3種方法。

let str = "12345678"let len1 = strlen(str) //8let len2 = str.count  //8let len3 = (str as NSString).length  //8

2、字串拼接:  使用加好或者append函數。

let str1 = "abc" + "cde"var str = "abc"str.append("cde")

3、字串遍曆:

let str = "abcdefg"for char in str {    print(char)}

let str = "abcdefg"for index in str.indices.indices {    print(str[index])   //通過下標訪問}

或帶下標

let str = "abcdefg"for (index, value) in str.enumerated() {    print("\(index) --- \(value)")}

4、字串全部大寫或小寫:

let str = "abcdefg"print(str.lowercased())  //全部小寫print(str.uppercased())  //全部大寫

5、多行字串使用3個雙引號。

let verse = """    To be, or not to be - that is the question;    Whether 'tis nobler in the mind to suffer    The slings and arrows of outrageous fortune,    Or to take arms against a sea of troubles,"""


6、ascii碼

let ascii = UnicodeScalar("a")?.value   //a的ascii碼print(ascii ?? "") //97


7、截取子字串

let str = "abcdefg"let indexD = str.index(of: "d")let sub = str[indexD!...] //defglet sub1 = str[indexD!..<str.endIndex] //defg  注意避免下標越界let sub2 = str[str.startIndex...indexD!] //abcd

let sub3 = (str as NSString).substring(to: 3)  //abclet sub4 = (str as NSString).substring(with: NSMakeRange(2, 3))  //cde

8、判斷是否含有字元(串)

let str = "abcdefg"print(str.contains("cd"))   //trueprint(str.contains("c"))    //trueprint(str.contains("o"))    //false

9、字串分割

//字串拆分(以單個或多個字元為分隔字元)let str = "abcdefg$$aaaa$$bbbb$$ccc"let des1 = (str as NSString).components(separatedBy: "$$")let des2 = str.components(separatedBy: "$$")print(des1)  //["abcdefg", "aaaa", "bbbb", "ccc"]print(des2) //["abcdefg", "aaaa", "bbbb", "ccc"]

10、字串替換:

let str = "abcdefg$$aaaa$$bbbb$$ccc"let dest11 = str.replacingOccurrences(of: "$$", with: "**")print(dest11)


進階篇:
1、擷取下標字元:

extension String {    //擷取下標對應的字元    func charAt(pos: Int) -> Character? {        if pos < 0 || pos >= count {            return nil   //判斷邊界條件        }        let index = self.index(self.startIndex, offsetBy: pos)        let str = self[index]        return Character(String(str))    }}let str = "abcdef"print(str.charAt(pos: 1)!)  //b

2、找出字串中最長的子串, 字串中包含中文、特殊字元、字母、數字等等。 思路: 使用正則找出所有字串, 然後按長度排序找到最長的。

//找出字串中英文字母最長的一個func LongestWord(_ sen: String) -> String {    let regx = try? NSRegularExpression(pattern: "[a-zA-Z]+", options: .caseInsensitive)        if let results = regx?.matches(in: sen, options: [], range: NSMakeRange(0, sen.count)) {        var array: [String] = []        for item in results {            let cur = (sen as NSString).substring(with: item.range)            array.append(cur)  //找出所有符合要求的字串        }        array.sort(by: { a,b in            if a.count > b.count {     //降序排列                return true            } else {                return false            }        })                return array[0]  //最長的字串    }        return sen}let ret = LongestWord("this is a test demo.1234324234穿插著中文和特殊字母@#@#adfsdfsdf!@#@$adfsdf")print(ret)  //adfsdfsdf


3、字串首字母變成大寫(考慮字串中有標點符號):

//首字母大寫, 要求支援標點func LetterCapitalize(_ str: String) -> String {        var result = ""    for i in 0..<str.count{        let cur = str.charAt(pos: i)        if i == 0 {            let tmp = String(cur!).uppercased()  //變成大寫            result.append(tmp)        } else {            let pre = str.charAt(pos: i-1)            //if pre is not character            if (UnicodeScalar(String(pre!))!.value >= UnicodeScalar("a")!.value && UnicodeScalar(String(pre!))!.value <= UnicodeScalar("z")!.value)                || (UnicodeScalar(String(pre!))!.value >= UnicodeScalar("A")!.value && UnicodeScalar(String(pre!))!.value <= UnicodeScalar("Z")!.value){                result.append(String(cur!))            } else {                result.append(String(cur!).uppercased())            }                    }    }        return result    }let ret = LetterCapitalize("this a test message")print(ret)


4、擷取UILable控制項顯示String需要的高度

extension String {    /**     * 查詢lable高度     * @param fontSize, 字型大小     * @param width, lable寬度     */    func getLableHeightByWidth(_ fontSize: CGFloat,                               width: CGFloat,                               font: UIFont) -> CGFloat {        let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)        let paragraphStyle = NSMutableParagraphStyle()        paragraphStyle.lineBreakMode = .byWordWrapping        let attributes = [NSFontAttributeName:font,                          NSParagraphStyleAttributeName:paragraphStyle.copy()]                let text = self as NSString        let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: attributes, context:nil)        return rect.size.height    }    }





相關文章

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.