2

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?

Matt
  • 14,906
  • 27
  • 99
  • 149
Janice Zhan
  • 571
  • 1
  • 5
  • 18

1 Answers1

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