Swift相当于String.format和.Replace?

时间:2016-04-26 17:04:07

标签: java ios swift

我有java代码片段。

functionReturnValue = String.format("%1$2s", jDay).replace(' ', '0') + "/" + String.format("%1$2s", i).replace(' ', '0') + "/" + dateIn.substring(0, 4);

这相当于什么? 这就是我到目前为止所拥有的

let string1 = String(format: "%1$2s", jDay);
let replacedString = String(string1.characters.map{$0 == " " ? "0" : $0})
let string2 = String(format: "%1$2s", i);
let replacedString2 = String(string2.characters.map{$0 == " " ? "0" : $0})
let string3 = dateIn[year];
let stringFinal = replacedString + "/" + replacedString2 + "/" + string3;

2 个答案:

答案 0 :(得分:2)

Swift和Java中的格式字符串不同,因此您无法使用%1$2s作为格式。此外,由于在您的Java代码中调用replace是为了添加前导零,您可以用格式调用替换它。最后,使用string interpolation构造最终字符串:

let s1 = String(format: "%02d", jDay)
let s2 = String(format: "%02d", i)
let s3 = dateIn[year]
let stringFinal = "\(s1)/\(s2)/\(s3)"

答案 1 :(得分:0)

万一有人想知道(就像我一样)你可以拥有多次转换的格式字符串,例如:

let hourPart = 5
let minutePart = 8
let isPm = true
let retStr = String(format: "%d:%02d %@", hourPart, minutePart, isPm ? "PM" : "AM")

给出“下午5:08”