In Swift, with the following string: "this is a string"
, how to obtain an array of the indexes where the character " "
(space) is present in the string?
Desired result: [4,7,9]
I've tried:
let spaces: NSRange = full_string.rangeOfString(" ")
But that only returns 4, not all the indexes.
Any idea?
Here's a simple approach — updated for Swift 5.6 (Xcode 13):
let string = "this is a string"
let offsets = string
.enumerated()
.filter { $0.element == " " }
.map { $0.offset }
print(offsets) // [4, 7, 9]
How it works:
enumerated()
enumerates the characters of the stringfilter
removes the characters for which the characters aren't spacesmap
converts the array of tuples to an array of just the indicesIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With