Swift中Int的前导零我想将IntSwift转换为String带有前导零的。例如,考虑以下代码:for myInt in 1 ... 3 { print("\(myInt)")}目前的结果是:123但我希望它是:010203在Swift标准库中有没有一种干净的方法呢?
3 回答
慕斯王
TA贡献1864条经验 获得超2个赞
假设你想要一个带有前导零的字段长度为2,你可以这样做:
import Foundationfor myInt in 1 ... 3 {
print(String(format: "%02d", myInt))}输出:
01 02 03
这在import Foundation技术上要求它不是Swift语言的一部分,而是Foundation框架提供的功能。请注意这两个import UIKit和import Cocoa包括Foundation所以它是没有必要的,如果你已导入再次导入Cocoa或UIKit。
格式字符串可以指定多个项目的格式。例如,如果您尝试格式化3小时,15分钟和7秒,03:15:07您可以这样做:
let hours = 3let minutes = 15let seconds = 7print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
输出:
03:15:07
凤凰求蛊
TA贡献1825条经验 获得超4个赞
对于左边填充,添加如下字符串扩展名:
Swift 2.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count if toPad < 1 { return self }
return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
}}Swift 3.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count if toPad < 1 { return self }
return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
}}使用此方法:
for myInt in 1...3 {
print("\(myInt)".padLeft(totalWidth: 2, with: "0"))}- 3 回答
- 0 关注
- 841 浏览
添加回答
举报
0/150
提交
取消
