how to make a string align to right? For now, I know how to make a string align to left by using stringByPaddingToLength
. Any idea for align to right?
Asked
Active
Viewed 2,477 times
2

Matt
- 14,906
- 27
- 99
- 149

Janice Zhan
- 571
- 1
- 5
- 18
-
2Possible duplicate of [Padding string to left](http://stackoverflow.com/questions/964322/padding-string-to-left) – Ozgur Vatansever May 14 '16 at 07:21
-
@ozgur I wanna it align to right, not left. – Janice Zhan May 14 '16 at 07:22
-
`stringByPaddingToLength` pads to right already. The link I've shared explains how to do the opposite *(pad to left)* using `stringByPaddingToLength`. – Ozgur Vatansever May 14 '16 at 07:22
-
*gazes into the future* `swiftpm install leftpad` – jtbandes May 14 '16 at 07:36
-
Could you give us example of results you wants ? – Julien Quere May 14 '16 at 10:03
1 Answers
3
A possible implementation (explanations 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))
}
}
}
Example usage:
let s = "foo"
let padded = s.stringByLeftPaddingToLength(6)
print(">" + padded + "<")
// > foo<
Update for 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))
}
}
}

Martin R
- 529,903
- 94
- 1,240
- 1,382