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截取字串(轉載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.