1

如何使字符串右对齐?现在,我知道如何使用stringByPaddingToLength. 任何想法对齐到正确?

4

1 回答 1

3

一个可能的实现(内联解释):

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))
        }
    }
}

示例用法:

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

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))
        }
    }
}
于 2016-05-14T10:12:59.207 回答