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 關注
- 790 瀏覽
添加回答
舉報
0/150
提交
取消