Swift中Int的前导零 [英] Leading zeros for Int in Swift
问题描述
我想将Swift中的 Int
转换为带有前导零的 String
。例如,考虑以下代码:
I'd like to convert an Int
in Swift to a String
with leading zeros. For example consider this code:
for myInt in 1...3 {
print("\(myInt)")
}
目前的结果是:
1
2
3
但我希望它是:
01
02
03
在Swift标准库中是否有一种干净的方法?
Is there a clean way of doing this within the Swift standard libraries?
推荐答案
假设你想要一个带有前导零的字段长度2,你可以这样做:
Assuming you want a field length of 2 with leading zeros you'd do this:
import Foundation
for myInt in 1...3 {
print(String(format: "%02d", myInt))
}
输出:
01
02
03
这需要 import Foundation
所以从技术上讲它不是Swift语言的一部分,而是由粉底
框架。请注意,导入UIKit
和导入Cocoa
包括基础
所以如果您已导入 Cocoa
或 UIKit
,则无需再次导入。
This requires import Foundation
so technically it is not a part of the Swift language but a capability provided by the Foundation
framework. Note that both import UIKit
and import Cocoa
include Foundation
so it isn't necessary to import it again if you've already imported Cocoa
or UIKit
.
格式字符串可以指定多个项目的格式。例如,如果您尝试格式化 3
小时, 15
分钟和 7
秒进入 03:15:07
你可以这样做:
The format string can specify the format of multiple items. For instance, if you are trying to format 3
hours, 15
minutes and 7
seconds into 03:15:07
you could do it like this:
let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
输出:
03:15:07
这篇关于Swift中Int的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!