Add subscript(r: Range<Int>) to String

Originator:robnapier
Number:rdar://17158813 Date Originated:04-Jun-2014
Status:Open Resolved:
Product:Swift Product Version:
Classification: Reproducible:
 
You should be able to slice strings by integers rather than hard-to-create StringIndexes. Here is a simple implementation:

import Foundation

extension String {
  subscript (r: Range<Int>) -> String { 
    get {
        return self.substringWithRange(
          Range(start: advance(self.startIndex, r.startIndex),
            end: advance(self.startIndex, r.endIndex)))
    }
  }
}

var s = "Hello, playground"

println(s[0 .. 5])

==> Hello

Comments

ellpisis .. ...

oops! When I suggested this "correction" above, I was not aware of the different range specifiers with .. (two dots) or ... (three dots) so, the "start + 1 is unnecessary.. Sorry.

suggestion for further improvement s[n] and s[n1..n2] and use of existing functions concatenated

extension String {

// single subscript s[n]


subscript (idx: Int) -> String
{
    get
    {
        return self.substringWithRange(
            Range( start: advance( self.startIndex, idx),
                end: advance( self.startIndex, idx + 1 )  )
        )
    }
}

// range subscript [n1..n2]
// end index corrected: added one so that
// e.g  "abcdefgh"[2..4] gives "cde" not "cdef" ..

subscript (r: Range<Int>) -> String
    {
    get
    {
        return self.substringWithRange(
            Range( start: advance( self.startIndex, r.startIndex),
                end: advance( self.startIndex, r.endIndex + 1 ))              )
    }
}

// N.B. there is no proper invalid range detection/assert in substringWitRange!
// it returns "characters" from memory exceeding the strings allocation!
//

// using existing functions concatenated

func substringFrom(start: Int, to: Int) -> String
{
    return (self.substringFromIndex(start)).substringToIndex(to - start + 1)
}

}

Evaluated in the XCode playground:

var s = "abcdefghijklmnopqrstuvwxyz"

var sub2 = s[4..12] //"efghijklm"

var c = s[5] // "f"

"abcdefgh"[2..4] // "cde"

let s2 = s.substringFrom(5, to: 24) // "fghijklmnopqrstuvwxy"

Kind Regards

Ted


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!