I'm used to do this in JavaScript:
var domains = "abcde".substring(0, "abcde".indexOf("cd")) // Returns "ab"
Swift doesn't have this function, how to do something similar?
I'm used to do this in JavaScript:
var domains = "abcde".substring(0, "abcde".indexOf("cd")) // Returns "ab"
Swift doesn't have this function, how to do something similar?
Doing this in Swift is possible but it takes more lines, here is a function
indexOf()
doing what is expected:This function is not optimized but it does the job for short strings.
In Swift 4 :
Getting Index of a character in a string :
Creating SubString (prefix and suffix) from String using Swift 4:
Output
If you want to generate a substring between 2 indices , use :
In the Swift version 3, String doesn't have functions like -
If the index is required for a substring, one of the ways to is to get the range. We have the following functions in the string which returns range -
For example to find the indexes of first occurrence of play in str
Note : range is an optional. If it is not able to find the String it will make it nil. For example
Tested for Swift 4.2/4.1/4.0/3.0
Using
String[Range<String.Index>]
subscript you can get the sub string. You need starting index and last index to create the range and you can do it as belowIf you don't define the start index this operator
..<
, it take the starting index. You can also usestr[str.startIndex..<range.lowerBound]
instead ofstr[..<range.lowerBound]
Xcode 9 • Swift 4 or later
usage:
There are three closely connected issues here:
All the substring-finding methods are over in the Cocoa NSString world (Foundation)
Foundation NSRange has a mismatch with Swift Range; the former uses start and length, the latter uses endpoints
In general, Swift characters are indexed using
String.Index
, not Int, but Foundation characters are indexed using Int, and there is no simple direct translation between them (because Foundation and Swift have different ideas of what constitutes a character)Given all that, let's think about how to write:
The substring
s2
must be sought ins
using a String Foundation method. The resulting range comes back to us, not as an NSRange (even though this is a Foundation method), but as a Range ofString.Index
(wrapped in an Optional, in case we didn't find the substring at all). However, the other number,from
, is an Int. Thus we cannot form any kind of range involving them both.But we don't have to! All we have to do is slice off the end of our original string using a method that takes a
String.Index
, and slice off the start of our original string using a method that takes an Int. Fortunately, such methods exist! Like this:Or, if you prefer to be able to apply this method directly to a string, like this...
...then make it an extension on String: