如何格式化String alignment-left

时间:2015-10-29 03:27:59

标签: ios string swift

首先,我发现我很容易格式化其他类型,例如Int,例如:

let i = 12345
let s = String(format: "%-10d", 12345)
//then s = "12345     "

右手边的几个空间正是我需要的!

但是当我尝试将它实现为String时(如果我使用"%@"我是对的)?

let str = "12345"
let s = String(format: "%-10@", str)
//then s = "12345" rather than "12345     "

我怎样才能达到相同的效果?

1 个答案:

答案 0 :(得分:5)

您可以使用String方法stringByPaddingToLength()

let str = "12345"
let paddedString = str.stringByPaddingToLength(10, withString: " ", startingAtIndex: 0)   // "12345     "

如果您想在字符串中添加前导字符您可以尝试创建自定义扩展名,如下所示:

extension String {
    func stringByAppendingLeadingCharacterToLength(newLenght: Int, withCharacter: Character) -> String {
        return newLenght-characters.count > 0 ? String(count: newLenght-characters.count, repeatedValue: withCharacter) + self : self
    }
}

let strNumbers = "12345"
let paddedString1 = strNumbers.stringByAppendingLeadingCharacterToLength(10, withCharacter: "0")  // "0000012345"

Xcode 8.2•Swift 3.0.2

extension String {
    func paddingLeft(with character: Character, maxLength: Int) -> String {
        return maxLength - characters.count > 0 ? String(repeating: String(character), count: maxLength - characters.count) + self : self
    }
}

用法:

"12345".paddingLeft(with: "0", maxLength: 10)   // "0000012345"