Last active
December 9, 2023 23:18
-
-
Save carlynorama/45b005db7bfa89e628d0db3795ad5e84 to your computer and use it in GitHub Desktop.
Int Extraction Sampler
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
//So MyString[3] just works. Don't use in projects with real input. | |
extension StringProtocol { | |
subscript(offset: Int) -> Character { | |
self[index(startIndex, offsetBy: offset)] | |
} | |
} | |
extension StringProtocol { | |
//Ignores negative signs. | |
func extractPositiveInts() -> [Int] { | |
self.components(separatedBy: CharacterSet.decimalDigits.inverted).compactMap({Int($0)}) | |
} | |
//Will find the neagive signs. Will not validate that they are negative signs in context. | |
func extractInts() -> [Int] { | |
self.components(separatedBy: CharacterSet.decimalDigits.inverted.union(CharacterSet(charactersIn:"-"))).compactMap({Int($0)}) | |
} | |
//Doesn't require Foundation, but does require a contains check. | |
func extractInts_splitWhere() -> [Int] { | |
self.split(whereSeparator: {!"-0123456789".contains($0)}).compactMap({Int($0)}) | |
} | |
//For when there is only one separator mixed in (only knocks out the seperator, so not really an extractInt) | |
func extractInts(separator:Self.Element) -> [Int] { | |
self.split(separator:separator).compactMap { Int($0)} | |
} | |
//Takes all the decimalDigits and slurps them into one number. | |
func schlurpPositiveInt() -> Int { | |
let filteredString = self.unicodeScalars.filter { | |
CharacterSet.decimalDigits.contains($0) | |
}.compactMap { Character($0) } | |
return Int(String(filteredString))! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment