Swift String Extension for finding the indices of all the numbers in a string

Alexandros Baramilis
1 min readApr 11, 2019

--

In plain words, we start from the startIndex of the string to look for decimalDigits characters. If we find something, we first check if it was preceded by a comma or a dot (if yes we add its index to the indices array), and then we also add the character index to the array. This accounts for any potential floating point numbers in the string, or for numbers with thousands separators. Then we move the searchStartIndex to the upperBound of the range of the character that we found, so we don’t keep finding the same character and so we don’t have to check the whole string again. When there are no remaining characters (range.isEmpty), we terminate the search.

Tests:

“”.indicesOfNumbers -> []

“0”.indicesOfNumbers -> [0]

“.5”.indicesOfNumbers -> [0, 1]

“1.5”.indicesOfNumbers -> [0, 1, 2]

“Mark”.indicesOfNumbers -> []

“Mark15”.indicesOfNumbers -> [4, 5]

“.Mark15.25s”.indicesOfNumbers -> [5, 6, 7, 8, 9]

“44.Mark15.25s”.indicesOfNumbers -> [0, 1, 7, 8, 9, 10, 11]

“.Mark15.f25s”.indicesOfNumbers -> [5, 6, 9, 10]

--

--