Swift如何使字符串向右对齐

Swift how to make a string align to right

如何使字符串右对齐? 现在,我知道如何使用stringByPaddingToLength使字符串向左对齐。 任何想法都正确吗?


可能的实现方式(内联说明):

1
2
3
4
5
6
7
8
9
10
11
12
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))
        }
    }
}

用法示例:

1
2
3
4
let s ="foo"
let padded = s.stringByLeftPaddingToLength(6)
print(">" + padded +"<")
// >   foo<

Swift 3更新:

1
2
3
4
5
6
7
8
9
10
11
12
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))
        }
    }
}