string - Swift 如何使字符串右对齐

标签 string swift right-align

如何使字符串右对齐?现在,我知道如何使用 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/

相关文章:

ios - 为 JSON Tableview 使用不同的 URL 链接

swift - 如何修复调整 View 大小时 CoreGraphics 虚线变化的问题

c - 在 C 中使用 printf_P 右对齐

python - 检查文本在 python 中是否右对齐

c++ - MFC - 如何将 WCHAR 转换为 CString?

C - 运行此应用程序时崩溃

python - 删除包含多个条件的列表条目

Swift 3 不正确的字符串插值与隐式展开的 Optionals

ios - 如何将 UInt8 数组转换为 Data? ( swift )

javascript - XML:如何将项目(HBox/Vbox 的按钮)右对齐