Last active
April 16, 2019 15:55
-
-
Save alexbaramilis/3e2fc9638a0c8b44eeca8739ac0134e9 to your computer and use it in GitHub Desktop.
Swift String Extension for finding the indices of all the numbers in a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
/// Returns the indices of all the numbers in the string. | |
/// | |
/// If a number is directly preceded by a dot/comma, the index of the dot/comma | |
/// will also be returned. | |
/// This accounts for potential numbers with decimal or thousands separators. | |
var indicesOfNumbers: [Int] { | |
var indices = [Int]() | |
var searchStartIndex = self.startIndex | |
while searchStartIndex < self.endIndex, | |
let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits, | |
range: searchStartIndex..<self.endIndex), | |
!range.isEmpty | |
{ | |
let index = distance(from: self.startIndex, to: range.lowerBound) | |
if index > 0 { | |
let previousIndex = self.index(self.startIndex, offsetBy: index - 1) | |
if let previousCharacter = self[previousIndex].unicodeScalars.first, | |
(previousCharacter == "." || previousCharacter == ",") | |
{ | |
indices.append(index - 1) | |
} | |
} | |
indices.append(index) | |
searchStartIndex = range.upperBound | |
} | |
return indices | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment