Swift 3 get start index (as int) substrings

I would like to get the start and end position of a substring inside a string. Example: in the line "Hello, this is my name"; if I provide the string "this", I would like to know that the starting index is 4 and the ending index is 7.

I found several links, including this one:

Swift: get the index of the beginning of the substring in the string a-substring-in-string

But it does not work in swift 3, since the method is now called a range.

Now I use this:

let range = mystring.range(of: "StringSearch")?.lowerBound 

which returns this

 Swift.String.UnicodeScalarView.Index(_position: 15), _countUTF16: 1)) 

And I can not get the position as an integer, since this is an index.

In general, I would like to have a position in an int variable, in this case 15.

Can anybody help me?

Thanks to everyone.

+8
substring indexing swift swift3
source share
2 answers

distance(from:to:) String method calculates the difference between two String.Index values:

 let mystring = "hi this is my name" if let range = mystring.range(of: "this") { let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound) let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound) print(startPos, endPos) // 3 7 } 

In fact, it just redirects the call to the CharacterView string, so the above gives the same result as

 let mystring = "hi this is my name" if let range = mystring.range(of: "this") { let startPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.lowerBound) let endPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.upperBound) print(startPos, endPos) // 3 7 } 

If you need all occurrences of a string:

 let mystring = "this is this and that is that" var searchPosition = mystring.startIndex while let range = mystring.range(of: "this", range: searchPosition..<mystring.endIndex) { let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound) let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound) print(startPos, endPos) searchPosition = range.upperBound } 
+14
source share

Martin R's adapted response to the function gives you the first occurrence as NSRange . You can also include it in extension of String .

 public class func indexOf(string: String, substring: String) -> NSRange? { if let range = string.range(of: substring) { let startPos = string.distance(from: string.startIndex, to: range.lowerBound) return NSMakeRange(startPos, substring.count) } } 
0
source share

All Articles