问题描述
我想将 Swift 中的 Int
转换为带有前导零的 String
.例如考虑这个代码:
for myInt in 1 ... 3 {打印((myInt)")}
目前的结果是:
123
但我希望它是:
010203
在 Swift 标准库中是否有一种干净的方法来做到这一点?
假设您希望字段长度为 2 且前导零,您可以这样做:
导入基础为 myInt 在 1 ... 3 {打印(字符串(格式:%02d",myInt))}
输出:
010203
这需要 import Foundation
,因此从技术上讲,它不是 Swift 语言的一部分,而是由 Foundation
框架提供的功能.请注意,import UIKit
和 import Cocoa
都包含 Foundation
,因此如果您已经导入了 ,则无需再次导入它可可
或 UIKit
.
格式字符串可以指定多个项目的格式.例如,如果您尝试将 3
小时、15
分钟和 7
秒格式化为 03:15:07
你可以这样做:
让小时= 3让分钟 = 15让秒 = 7打印(字符串(格式:%02d:%02d:%02d",小时,分钟,秒))
输出:
03:15:07
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)")
}
Currently the result of it is:
1
2
3
But I want it to be:
01
02
03
Is there a clean way of doing this within the Swift standard libraries?
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))
}
output:
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
.
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))
output:
这篇关于Swift 中 Int 的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!