-2

I'm searching for a build-in function for converting a string like "01092030" (format "[[dd]hh]mmss") to four individual integers.

  • dd => 01
  • hh => 09
  • mm => 20
  • ss => 30

dd and hh are optional. If missing they should be 0. I could do it by by developing a special function, but I like to use something like a regular expression.

Peter71
  • 2,180
  • 4
  • 20
  • 33
  • 1
    "I'm searching for a build-in function" Why? You don't want to write any code? "but I like to use something like a regular expression" Fine, but even if you could do that you'd still be writing code. What's the point of your "without special function" caveat? – matt May 20 '16 at 16:00
  • Why would you use regular expressions for this? In any case, regex or not, that code belongs in its own function. – Alexander May 20 '16 at 16:12
  • I meant, that I want to use a flexible definition, instead of a special implementation for this case. I have a function which checks each position of the string step by step. But the solution of matt looks more elegant to me. – Peter71 May 20 '16 at 16:19

2 Answers2

3

I don't see the point of your "build-in function" or "regular expression" requirements, but whatever...

let s = "092030" as NSString
let pattern = "\\d\\d"
let reg = try! NSRegularExpression(pattern: pattern, options: [])
let matches = reg.matchesInString(s as String, options: [], range: NSMakeRange(0, s.length))
var result = matches.map {s.substringWithRange($0.range)}
while result.count < 4 {
    result.insert("0", atIndex: 0)
}
// result is: ["0", "09", "20", "30"]

I'm also a little unclear on your output requirements. On the one hand, you say you want four "individual integers". But "09" is not an integer; it's a string representing an integer. So it seems to me that you actually want strings. If so, then result is the desired result. If not, then you need one more step:

let result2 = result.map{Int($0)!}
// result2 is: [0, 9, 20, 30]
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Yes, you are right. 09 should indicate, that the 0 belongs to 9, which results in 9. The solution is excellent! Exactly what I searched for (including converting to int). Why is use of "pattern" not necessary (and this is a regular expression)? – Peter71 May 20 '16 at 16:17
1

Since the string contains date components you could alternatively use NSDateFormatter

let string  = "01092030"

let dateFormatter = NSDateFormatter()
let dayMissing = string.characters.count < 8
let hourMissing = string.characters.count < 6
dateFormatter.dateFormat = hourMissing ? "mmss" : dayMissing ? "HHmmss" : "ddHHmmss"
let date = dateFormatter.dateFromString(string)!
let components = NSCalendar.currentCalendar().components([.Day, .Hour, .Minute, .Second], fromDate: date)
let second = components.second
let minute = components.minute
let hour = components.hour
let day = dayMissing ? 0 : components.day
vadian
  • 274,689
  • 30
  • 353
  • 361