我想将Swift中的Int
转换为具有前导零的String
。例如,考虑以下代码:
for myInt in 1 ... 3 {
print("\(myInt)")
}
目前它的结果是:
1
2
3
但我希望它是:
01
02
03
在Swift标准库中有没有一种干净的方法来做到这一点?
发布于 2019-08-22 16:02:25
Swift 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
发布于 2021-02-12 03:48:08
使用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`
发布于 2018-05-06 16:27:07
如果您仅使用格式字符串处理数字,则其他答案也很好,但当您可能有需要填充的字符串时,这是很好的(虽然无可否认与问题略有不同,但在本质上看起来很相似)。此外,如果字符串比焊盘长,也要小心。
let str = "a str"
let padAmount = max(10, str.count)
String(repeatElement("-", count: padAmount - str.count)) + str
输出"-----a str"
https://stackoverflow.com/questions/25566581
复制相似问题