Swift - search for a character at multiple positions in a string
In Swift with the following line: "this is a string", how do I get an array of indices where the character "" (space) is present in the string?
Desired result: [4,7,9]
I tried:
let spaces: NSRange = full_string.rangeOfString(" ")
But this only returns 4, not all indices.
Any idea?
+3
source to share
2 answers
Here's a simple approach:
let string = "this is a string"
let indices = string
.characters
.enumerate()
.filter { $0.element == " " }
.map { $0.index }
print(indices) // [4, 7, 9]
-
characters
returnsCharacterView
which isCollectionType
(similar to an array of single characters) -
enumerate
converts this collection toSequenceType
tuples containingindex
(0 to 15) andelement
(every single character) -
filter
removes tuples for which characters are not spaces -
map
converts an array of tuples to an array of indices only
This approach requires Swift 2 (in Xcode 7 beta). From the comments, the Swift 1.2 syntax is:
let indices = map(filter(enumerate(string), { $0.element == " " }), { $0.index } )
(tip for Martin R hat ).
+7
source to share
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]
0
source to share