Swift 字符串截取

  1. 截取前三个字符

     //方法一        
     let str = "0123456789"
     let subStr = str.prefix(3)
     print(subStr)//输出012
    
     //方法二
     let str = "0123456789"
     let endIndex =  str.index(str.startIndex, offsetBy: 3)
     let newStr = String(str[..
  2. 截取第三个到第六个范围内的字符

     let str = "0123456789"
     let startIndex = str.index(str.startIndex, offsetBy: 3)
     let endIndex =  str.index(str.startIndex, offsetBy: 6)
     let newStr = String(str[startIndex..
  3. 截取后三个字符

     //方法一
     let str = "0123456789"
     let subStr = str.suffix(3)
     print(subStr)//输出789
     
     //方法二
     let str = "0123456789"
     let startIndex =  str.index(str.endIndex, offsetBy: -3)
     let newStr = String(str[startIndex..

你可能感兴趣的:(Swift 字符串截取)