Swift 4.0 字串擷取,拼接,字串富文字顯示

東閣堂主發表於2018-04-03

字串擷取,呼叫系統方法

 let testStr = "hello world"
    //這種方法和swift3.2 類似
 let index1 = testStr.index(testStr.endIndex, offsetBy: -5) 
 let test1 = String(testStr.suffix(from: index1))
 //test1 = "hello" 
        
 let index2 = testStr.index(testStr.startIndex, offsetBy: 5)
 let test2 = String(testStr.prefix(upTo: index2))//
 //test1 = "world" 
 //當然你也可以這樣,是不是更簡潔了
 let test3 = String(testStr.suffix(5))
 //test3 = "hello" 
 let test4 = String(testStr.prefix(5))
 //test3 = "world"       
 let subString = (testStr as NSString).substring(with: NSMakeRange(2,3))
 //subString = "llo"
複製程式碼

字串拼接

# 字串拼接很簡單
let test1 = "hello"
let test2 = "world"
let test = test1 + " " + test2
// test = "hello world"
let index = 2
let testInt = test + "\(index)" 
// testInt = "hello world2"
複製程式碼

字串富文字

let tmpString = "我有很多的很多錢?,哈哈哈!"
let range = NSRange(location: 4, length: (balance as NSString).length)
let attriString = NSMutableAttributedString(string: tmpString)
attriString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hex:"#EA4B44"), range: range)
label.attributedText = attriString
# 同時設定多個屬性
 let att = [ NSAttributedStringKey.foregroundColor: textColor,
 NSAttributedStringKey.font: UIFont.systemFont(ofSize: textFont), 
 NSAttributedStringKey.backgroundColor: textBgColor]
 attriString.addAttribute(att , range: range)

複製程式碼

字串擷取,呼叫系統方法 swift 3.2 版本:

let sessionId = "this is a test"

let index = sessionId.index(sessionId.endIndex, offsetBy: -2)

let suffix = sessionId.substring(from: index)

最後結果為:“st”

獲取開頭字元兩個:

let sessionId = "this is a test"

let index = sessionId.index(sessionId.startIndex, offsetBy: 2)

let prefix = sessionId.substring(to: index)

獲取中間字元兩個:

a,笨方法

let sessionId = "this is a test"

let index = sessionId.index(sessionId.startIndex, offsetBy: 5)

let prefix = sessionId.substring(to: index)

let index = sessionId.index(prefix.startIndex, offsetBy: -2)

b,直接用range擷取

let subString1 = (swiftString as NSString).substring(with: NSMakeRange(1,3))
複製程式碼

相關文章