Swift intercept string (reprint)

Source: Internet
Author: User

Swift 3 String has three methods for string interception:

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

Examples used to do the demonstration:

var str = "Hello, World"

Str.substring (To:String.Index)

This method intercepts the index specified by the parameter from the beginning of the string to .

let index = str.index(str.startIndex, offsetBy: 5)  //索引为从开始偏移5个位置str.substring(to: index)  // 获取Hello

SUBSTRING (from:String.Index)

This method intercepts the from end of the string from the index specified by the parameter.

let index = str.index(str.startIndex, offsetBy: 7) //索引从开始偏移7个位置str.substring(from: index)  // 输出World

Str.substring (with:range<string.index>)

This method intercepts the specified string range, which is specified by range. Similar to the 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 intercept string (reprint)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.