[Swift] How to use range to intercept substrings

Source: Internet
Author: User

Original: How to Find a Substring in Range of a Swift String

There is a big difference between ranges in swift and Objective-c in Nsrange, and I find it takes more time than I thought to deal with ranges related issues in Swift. However, now look back and find that the use of ranges in Swift is reasonable, but the need for proper use of ranges really requires some special skill.

To see an example, the following code shows a substring that intercepts the beginning of a specified character and ends with a specified character:

var str = "Hello, playground" Let Rangeofhello = Range (Start:str.startIndex, End:advance (Str.sta Rtindex, 5)) Let Hellostr = Str.substringwithrange (Rangeofhello) hellostr//"Hello"

You can see that you cannot get a range by specifying an int value that begins to end, you need to use the startIndex and endIndex properties of the String class (string.startindex Type is not an int), which is the special place for swift ranges.

To get a range beyond startindex, you can use the advance function in the code above. Advance can also be used to calculate from the end, so if you need to get index relative to Endindex, like the following code, use a negative number:

Let DOB = "01/01/2000" Let Rangeofyear = Range (start: (Advance (Dob.endindex,-4)), End:dob.endInde x) Let Yearstr = Dob.substringwithrange (rangeofyear) YEARSTR//"2000"

I have to say, think carefully, Swift's use of ranges is very clean and elegant, as long as you are familiar with its usage.

[Swift] How to use range to intercept substrings

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.