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

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

目前的结果是:

1
2
3

但我希望它是:

01
02
03

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


当前回答

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"

其他回答

下面的代码生成了一个前面填充为0的3位字符串:

import Foundation

var randomInt = Int.random(in: 0..<1000)
var str = String(randomInt)
var paddingZero = String(repeating: "0", count: 3 - str.count)

print(str, str.count, paddingZero + str)

输出:

5 1 005
88 2 088
647 3 647

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

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"))
}

假设你想要一个长度为2且前导为0的字段,你可以这样做:

import Foundation

for myInt in 1 ... 3 {
    print(String(format: "%02d", myInt))
}

输出:

01 02 03

这需要导入Foundation,所以从技术上讲,它不是Swift语言的一部分,而是Foundation框架提供的功能。请注意,import UIKit和import Cocoa都包含Foundation,所以如果你已经导入了Cocoa或UIKit,就没有必要再次导入它。


格式字符串可以指定多个项的格式。例如,如果你想把3小时15分7秒格式化为03:15:07,你可以这样做:

let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))

输出:

03:15:07

Swift 4*及以上,你也可以试试这个:

func leftPadding(valueString: String, toLength: Int, withPad: String = " ") -> String {
        guard toLength > valueString.count else { return valueString }
        
        let padding = String(repeating: withPad, count: toLength - valueString.count)
        return padding + valueString
    }

调用函数:

leftPadding(valueString: "12", toLength: 5, withPad: "0")

输出: “00012”

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"