Swift ios - substring : Cắt chuỗi string trong swift

Hướng dẫn cắt chuỗi String trong swift - ios

  1. Chuỗi chúng ta xử lý sẽ khai báo như sau
      var array:[String] = "chung ta can cat chuoi nay nhu the nao"

      -  Cắt bỏ chữ đầu tiên và chữ cuối c  : dropFirst() - dropLast()
  • Cắt chữ đầu tiên  :    array.characters. dropFirst()  
          -> KQ: "hung ta can cat chuoi nay nhu the nao"
  • Cắt chữ cuối cùng:   array.characters. dropLast()  
          -> KQ: "chung ta can cat chuoi nay nhu the na"
  • Cắt chuỗi theo vị trí bắt đầu và kết thúc: 
    substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(1), end: str.endIndex.advancedBy(0)))
        str.endIndex.advancedBy(0)) -> bắt đầu vị trí index = 0
        str.startIndex.advancedBy(1) -> cắt đến vị trí index = 1
        vd: 
        -   array.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(1),       end: str.endIndex.advancedBy(0)))
        -> Kết quả :  "hung ta can cat chuoi nay nhu the nao"

       -   array.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(5),       end: str.endIndex.advancedBy(0)))
         -> Kết quả : "ta can cat chuoi nay nhu the nao"
      - Loại từ vị trí index = 0 đến vị trí i : substringFromIndex(str.startIndex.advancedBy(i))

      ->  array.substringFromIndex(str.startIndex.advancedBy(2))
      -> KQ:  "ung ta can cat chuoi nay nhu the nao"

  • substringToIndex(str.startIndex.advancedBy(3))  -> Lấy từ phần tử 0 - > 3

Comments

Popular posts from this blog

Tranquil Tunes: Soothing Piano & Guitar Music for Study, Work, Relaxation & Meditation

Resize - Rotate - Move View or image view in swift

NSTimer - Tạo ứng dụng đếm thời gian swift-ios