我想将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标准库中是否有一种干净的方式来做到这一点?
当前回答
假设你想要一个长度为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
其他回答
下面的代码生成了一个前面填充为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"))
}
斯威夫特5
@imanuo answers已经很棒了,但如果你正在使用一个充满数字的应用程序,你可以考虑这样的扩展:
extension String {
init(withInt int: Int, leadingZeros: Int = 2) {
self.init(format: "%0\(leadingZeros)d", int)
}
func leadingZeros(_ zeros: Int) -> String {
if let int = Int(self) {
return String(withInt: int, leadingZeros: zeros)
}
print("Warning: \(self) is not an Int")
return ""
}
}
这样你可以在任何地方打电话:
String(withInt: 3)
// prints 03
String(withInt: 23, leadingZeros: 4)
// prints 0023
"42".leadingZeros(2)
// prints 42
"54".leadingZeros(3)
// prints 054
如果您只使用格式字符串处理数字,那么其他答案都很好,但是当您可能有需要填充的字符串时,这个答案也很好(尽管不可否认与所问的问题略有不同,但在精神上似乎是相似的)。此外,如果弦比衬垫长,要小心。
let str = "a str"
let padAmount = max(10, str.count)
String(repeatElement("-", count: padAmount - str.count)) + str
输出“-----a str”
细节
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)")
}