Swift 4.0 字符串截取,拼接,字符串富文本顯示

字符串截取,調用系統方法

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))
複製代碼
相關文章
相關標籤/搜索