# index indexes and ranges of String

**URL:** <https://forums.swift.org/t/index-indexes-and-ranges-of-string/4830>\
**Category:** Discussion\
**Created:** [January 6, 2017, 2:39pm UTC](https://forums.swift.org/t/index-indexes-and-ranges-of-string/4830 "2017-01-06T14:39:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Carlos\_Garcia](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/carlos_garcia/32/11608_2.png) [@Carlos\_Garcia](https://forums.swift.org/u/Carlos_Garcia)\
**Post date:** [January 6, 2017, 2:39pm UTC](https://forums.swift.org/t/index-indexes-and-ranges-of-string/4830/1 "2017-01-06T14:39:47Z")

</div>

Hi,

I think this is important enough and useful for we to be in the core standard library

extension String {

&nbsp;&nbsp;&nbsp;&nbsp;func index(of string: String, options: String.CompareOptions = .literal) -\> String.Index? {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return range(of: string, options: options)?.lowerBound  
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;func indexes(of string: String, options: String.CompareOptions = .literal) -\> [String.Index] {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var result: [String.Index] =   
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var start = startIndex  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while let range = range(of: string, options: options, range: start..\<endIndex) {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.append(range.lowerBound)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;start = range.upperBound  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return result  
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;func ranges(of string: String, options: String.CompareOptions = .literal) -\> [Range\<String.Index\>] {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var result: [Range\<String.Index\>] =   
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var start = startIndex  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while let range = range(of: string, options: options, range: start..\<endIndex) {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.append(range)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;start = range.upperBound  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return result  
&nbsp;&nbsp;&nbsp;&nbsp;}

}

Source is not mine, I’ve found here: [Index of a substring in a string with Swift - Stack Overflow](http://stackoverflow.com/a/32306142/4550651)

Carlos García
