in swift, following string: "this string", how obtain array of indexes character " " (space) present in string?
desired result: [4,7,9]
i've tried:
let spaces: nsrange = full_string.rangeofstring(" ") but returns 4, not indexes.
any idea?
here's simple approach:
let string = "this string" let indices = string .characters .enumerate() .filter { $0.element == " " } .map { $0.index } print(indices) // [4, 7, 9] charactersreturnscharacterview,collectiontype(similar array of individual characters)enumerateconverts collectionsequencetypeof tuples containingindex(0 through 15) ,element(each individual character)filterremoves tuples characters aren't spacesmapconverts array of tuples array of indices
this approach requires swift 2 (in xcode 7 beta). comments, swift 1.2 syntax:
let indices = map(filter(enumerate(string), { $0.element == " " }), { $0.index } ) (hat tip martin r).
Comments
Post a Comment