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 = "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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,746评论 4 61
  • 这个周开始了一个新项目的开发,现在主要进行需求评审,而我的工作就是对已有模块进行测试用例的编写。感谢3.5号五娃的...
    悠悠然123阅读 261评论 0 0
  • 我是一个刚毕业的大学生,家庭条件不是很好,从记事开始(我记事比较晚) 父母就离异啦,我还有一个弟弟,是母亲...
    钟子涵阅读 316评论 1 1

友情链接更多精彩内容