如何使字符串右对齐?现在,我知道如何使用 stringByPaddingToLength
使字符串左对齐。有向右对齐的想法吗?
最佳答案
可能的实现(内联解释):
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))
}
}
}
关于string - Swift 如何使字符串右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223640/