Swift截取字串(轉載)

來源:互聯網
上載者:User

標籤:截取字串   輸出   ring   dex   tin   樣本   with   rom   string   

Swift 3的String有三個方法用於做字串截取:

str.substring(to: String.Index)str.substring(from: String.Index)str.substring(with: Range<String.Index>)

用於做示範的樣本:

var str = "Hello, World"

str.substring(to: String.Index)

這個方法會從字串的開始截取到to參數指定的索引。

let index = str.index(str.startIndex, offsetBy: 5)  //索引為從開始位移5個位置str.substring(to: index)  // 擷取Hello

substring(from: String.Index)

這個方法會從from參數指定的索引截取到字串的末尾。

let index = str.index(str.startIndex, offsetBy: 7) //索引從開始位移7個位置str.substring(from: index)  // 輸出World

str.substring(with: Range<String.Index>)

這個方法是截取指定的字串範圍,範圍由Range指定。類似於Swift 2的String.substringWithRange

let start = str.index(str.startIndex, offsetBy: 7)  //索引從開始位移7個位置let end = str.index(str.endIndex, offsetBy: -3)   //所有從末尾往回位移三個位置let range = start..<endstr.substring(with: range)  // 輸出Wo

Swift截取字串(轉載)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.