Swift - Find character at several positions within string -


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] 
  • characters returns characterview, collectiontype (similar array of individual characters)
  • enumerate converts collection sequencetype of tuples containing index (0 through 15) , element (each individual character)
  • filter removes tuples characters aren't spaces
  • map converts 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