美文网首页
Swift 4.0 字符串截取,拼接,字符串富文本显示

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

作者: _东阁堂主_ | 来源:发表于2018-04-03 15:13 被阅读43次

字符串截取,调用系统方法

 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 = "world"    
 let test4 = String(testStr.prefix(5))
  //test4 = "hello"    
 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))

相关文章

网友评论

      本文标题:Swift 4.0 字符串截取,拼接,字符串富文本显示

      本文链接:https://www.haomeiwen.com/subject/bqxchftx.html