Eine mögliche Implementierung (Erklärungen inline):
extension String {
func stringByLeftPaddingToLength(newLength : Int) -> String {
let length = self.characters.count
if length < newLength {
// Prepend `newLength - length` space characters:
return String(count: newLength - length, repeatedValue: Character(" ")) + self
} else {
// Truncate to the rightmost `newLength` characters:
return self.substringFromIndex(startIndex.advancedBy(length - newLength))
}
}
}
Beispiel Nutzung:
let s = "foo"
let padded = s.stringByLeftPaddingToLength(6)
print(">" + padded + "<")
// > foo<
Update für Swift 3:
extension String {
func stringByLeftPaddingTo(length newLength : Int) -> String {
let length = self.characters.count
if length < newLength {
// Prepend `newLength - length` space characters:
return String(repeating: " ", count: newLength - length) + self
} else {
// Truncate to the rightmost `newLength` characters:
return self.substring(from: self.index(endIndex, offsetBy: -newLength))
}
}
}
Mögliche Duplikat [Padding s tring nach links] (http://stackoverflow.com/questions/964322/padding-string-to-left) – ozgur
@ozgur Ich möchte es rechts ausrichten, nicht links. –
'stringByPaddingToLength' Pads nach rechts bereits. Der Link, den ich geteilt habe, erklärt, wie man das Gegenteil macht * (Pad nach links) * mit 'stringByPaddingToLength'. – ozgur