Reputation: 141
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?
Upvotes: 4
Views: 396
Reputation: 66292
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 indicesUpvotes: 8
Reputation: 285170
A solution for Swift 1.2 using Regex
func searchPattern(pattern : String, inString string : String) -> [Int]?
{
let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(), error: nil)
return regex?.matchesInString(string, options: NSMatchingOptions(), range: NSRange(location:0, length:count(string)))
.map { ($0 as! NSTextCheckingResult).range.location }
}
let string = "this is a string"
searchPattern("\\s\\S", inString : string) // [4, 7, 9]
searchPattern("i", inString : string) // [2, 5, 13]
Upvotes: 0