小胖说swift05--------swift中字符串截取方法(substring)

前端之家收集整理的这篇文章主要介绍了小胖说swift05--------swift中字符串截取方法(substring)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. var s="1234567890"
  2.  
  3. let index = s.startIndex.advancedBy(5) //swift 2.0+
  4. let index2 = s.endIndex.advancedBy(-6) //swift 2.0+
  5. var range = Range<String.Index>(start: index2,end: index)
  6.  
  7. var s1:String=s.substringFromIndex(index)
  8. var s2:String=s.substringToIndex(index2)
  9. var s3=s.substringWithRange(range)
  10.  
  11. print(s1)//67890
  12. print(s2)//1234
  13. print(s3)//5
  14.  
  15. // 扩展String
  16.  
  17. extension String {
  18. subscript (r: Range<Int>) -> String {
  19. get {
  20. let startIndex = self.startIndex.advancedBy(r.startIndex)
  21. let endIndex = self.startIndex.advancedBy(r.endIndex)
  22.  
  23. return self[Range(start: startIndex,end: endIndex)]
  24. }
  25. }
  26. }
  27.  
  28. var s4 = s[2...4]
  29. print(s4);//345

猜你在找的Swift相关文章