字符串格式问题 - Swift

时间:2017-12-30 03:30:18

标签: ios swift string

我有一个函数,我用它来格式化一个字符串。字符串是这样的" PT1H3M20S"这意味着1小时3分20秒。在我的函数中,我想将字符串格式化为1:03:20并且它工作正常但有时候,我得到这样的字符串" PT1H20S"这意味着1小时20秒,我的功能格式就像1:20这样让人们把它读成1分20秒。有什么建议吗?

func formatDuration(videoDuration: String) -> String{
    let formattedDuration = videoDuration.replacingOccurrences(of: "PT", with: "").replacingOccurrences(of: "H", with:":").replacingOccurrences(of: "M", with: ":").replacingOccurrences(of: "S", with: "")
    let components = formattedDuration.components(separatedBy: ":")
    var duration = ""
    for component in components {
        duration = duration.count > 0 ? duration + ":" : duration
        if component.count < 2 {
            duration += "0" + component
            continue
        }
        duration += component
    }
    // instead of 01:10:10, display 1:10:10
    if duration.first == "0"{
        duration.remove(at: duration.startIndex)
    }
    return duration
}

称之为:

print(formatDuration(videoDuration: "PT1H15S")

3 个答案:

答案 0 :(得分:2)

由于您需要查看每个号码后面的单位,因此无法从字符串中删除单位开始。

这是一个使用Scanner来解析原始字符串并找到构建最终结果的小时数,分钟数和秒数的解决方案。

这也将返回值更改为可选,以指示传入的字符串无效。

func formatDuration(videoDuration: String) -> String? {
    let scanner = Scanner(string: videoDuration)
    if scanner.scanString("PT", into: nil) {
        var hours = 0
        var mins = 0
        var secs = 0
        let units = CharacterSet(charactersIn: "HMS")
        while !scanner.isAtEnd {
            var num = 0
            if scanner.scanInt(&num) {
                var unit: NSString?
                if scanner.scanCharacters(from: units, into: &unit) {
                    switch unit! {
                    case "H":
                        hours = num
                    case "M":
                        mins = num
                    case "S":
                        secs = num
                    default:
                        return nil // Invalid unit
                    }
                } else {
                    return nil // No unit after the number
                }
            } else {
                return nil // No integer
            }
        }

        if hours > 0 {
            return String(format: "%d:%02d:%02d", hours, mins, secs)
        } else {
            return String(format: "%02d:%02d", mins, secs)
        }
    } else {
        return nil // No leading PT
    }
}

print(formatDuration(videoDuration: "PT1H3M20S") ?? "bad")
print(formatDuration(videoDuration: "PT1H15S") ?? "bad")
print(formatDuration(videoDuration: "PT4M6") ?? "bad")

输出:

  

1点03分20秒
  1点零零分15秒
  坏

答案 1 :(得分:1)

在你的情况下,你的字符串几分钟内没有字符,所以你可以检查字符串是否包含分钟,然后在1:20之间添加“00:”并适当格式化。

答案 2 :(得分:0)

您还可以搜索小时,分钟和秒的索引,并使用DateComponentsFormatter位置样式格式化视频时长:

创建静态位置日期组件格式化程序:

extension Formatter {
    static let positional: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .positional
        return formatter
    }()
}

您的格式持续时间方法:

func formatVideo(duration: String) -> String {
    var duration = duration
    if duration.hasPrefix("PT") { duration.removeFirst(2) }
    let hour, minute, second: Double
    if let index = duration.index(of: "H") {
        hour = Double(duration[..<index]) ?? 0
        duration.removeSubrange(...index)
    } else { hour = 0 }
    if let index = duration.index(of: "M") {
        minute = Double(duration[..<index]) ?? 0
        duration.removeSubrange(...index)
    } else { minute = 0 }
    if let index = duration.index(of: "S") {
        second = Double(duration[..<index]) ?? 0
    } else { second = 0 }
    return Formatter.positional.string(from: hour * 3600 + minute * 60 + second) ?? "0:00"
}
let duration = "PT1H3M20S"
formatVideo(duration: duration)  // "1:03:20"