我想将Swift中的Int转换为带前导零的字符串。例如,考虑以下代码:
for myInt in 1 ... 3 {
print("\(myInt)")
}
目前的结果是:
1
2
3
但我希望它是:
01
02
03
在Swift标准库中是否有一种干净的方式来做到这一点?
我想将Swift中的Int转换为带前导零的字符串。例如,考虑以下代码:
for myInt in 1 ... 3 {
print("\(myInt)")
}
目前的结果是:
1
2
3
但我希望它是:
01
02
03
在Swift标准库中是否有一种干净的方式来做到这一点?
当前回答
使用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`
其他回答
在Xcode 8.3.2, iOS 10.3 这对现在来说很好
Sample1:
let dayMoveRaw = 5
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05
Sample2:
let dayMoveRaw = 55
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55
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"
细节
Xcode 9.0.1, swift 4.0
解决方案
Data
import Foundation
let array = [0,1,2,3,4,5,6,7,8]
解决方案1
extension Int {
func getString(prefix: Int) -> String {
return "\(prefix)\(self)"
}
func getString(prefix: String) -> String {
return "\(prefix)\(self)"
}
}
for item in array {
print(item.getString(prefix: 0))
}
for item in array {
print(item.getString(prefix: "0x"))
}
解决方案2
for item in array {
print(String(repeatElement("0", count: 2)) + "\(item)")
}
解决方案3
extension String {
func repeate(count: Int, string: String? = nil) -> String {
if count > 1 {
let repeatedString = string ?? self
return repeatedString + repeate(count: count-1, string: repeatedString)
}
return self
}
}
for item in array {
print("0".repeate(count: 3) + "\(item)")
}
下面的代码生成了一个前面填充为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"))
}