我想将Swift中的Int转换为带前导零的字符串。例如,考虑以下代码:

for myInt in 1 ... 3 {
    print("\(myInt)")
}

目前的结果是:

1
2
3

但我希望它是:

01
02
03

在Swift标准库中是否有一种干净的方式来做到这一点?


当前回答

与其他使用格式化器的答案不同,你也可以在循环内的每个数字前面添加一个“0”文本,就像这样:

for myInt in 1...3 {
    println("0" + "\(myInt)")
}

但是,当您必须为每个单独的数字添加指定数量的0时,formatter通常更好。如果你只需要加一个0,那么它就是你的选择。

其他回答

对于左填充,添加一个字符串扩展,如下所示:

Swift 5.0 +

extension String {

    func padLeft(totalWidth: Int, with byString: String) -> String {
        let toPad = totalWidth - self.count
        if toPad < 1 {
            return self
        }
    
        return "".padding(toLength: toPad, withPad: byString, startingAt: 0) + self
    }
}

使用这种方法:

for myInt in 1...3 {
    print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}

与其他使用格式化器的答案不同,你也可以在循环内的每个数字前面添加一个“0”文本,就像这样:

for myInt in 1...3 {
    println("0" + "\(myInt)")
}

但是,当您必须为每个单独的数字添加指定数量的0时,formatter通常更好。如果你只需要加一个0,那么它就是你的选择。

使用Swift 5新奇的可扩展插值:

extension DefaultStringInterpolation {
    mutating func appendInterpolation(pad value: Int, toWidth width: Int, using paddingCharacter: Character = "0") {
        appendInterpolation(String(format: "%\(paddingCharacter)\(width)d", value))
    }
}

let pieCount = 3
print("I ate \(pad: pieCount, toWidth: 3, using: "0") pies")  // => `I ate 003 pies`
print("I ate \(pad: 1205, toWidth: 3, using: "0") pies")  // => `I ate 1205 pies`

Swift 3.0 +

左填充字符串扩展,类似于填充(toLength:withPad:startingAt:)在基础

extension String {
    func leftPadding(toLength: Int, withPad: String = " ") -> String {

        guard toLength > self.characters.count else { return self }

        let padding = String(repeating: withPad, count: toLength - self.characters.count)
        return padding + self
    }
}

用法:

let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"

如果您只使用格式字符串处理数字,那么其他答案都很好,但是当您可能有需要填充的字符串时,这个答案也很好(尽管不可否认与所问的问题略有不同,但在精神上似乎是相似的)。此外,如果弦比衬垫长,要小心。

   let str = "a str"
   let padAmount = max(10, str.count)
   String(repeatElement("-", count: padAmount - str.count)) + str

输出“-----a str”