I am new to Swift and I was looking for some help, please.
I have a String
let someString = "Here is an example of string"
I want to get is an example
part of it.
In Java I can do something like:
String someString = "Here is an example of string"
String s = someString.substring(someString.indexOf("is "), someString.indexOf(" of"));
I was wondering if there is anything similar in Swift to Java's
String.indexOf("some string")
in order to find an index of the element of String. I've looked around and couldn't find anything.
What I need it for is to find startIndex
and endIndexes
of a string that I am going to substring. I understand that it can be done easier with something like string.endIndex.advanceBy(-9)
, but string I am looking to go through is a couple of paragraphs long.
Found the solution:
NSString.range(of: "string").location
returns the index I've been looking for in case anyone wondering
UPDATE
Leo's answer works as well for anyone looking for an alternative:
Note that you should make sure to only search the range " of" string after the occurrence to the "is ".
if let lower = someString.range(of: "is ")?.upperBound, let upper = someString.range(of: " of", range: lower..<someString.endIndex)?.lowerBound { let substring = someString[lower..<upper] // "an example" }