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