Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Find character at several positions within string

Tags:

string

swift

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?

like image 746
arj Avatar asked Mar 16 '23 10:03

arj


1 Answers

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 string
  • filter removes the characters for which the characters aren't spaces
  • map converts the array of tuples to an array of just the indices
like image 148
Aaron Brager Avatar answered Mar 18 '23 00:03

Aaron Brager