Padding a swift String for printing

前端 未结 6 677
迷失自我
迷失自我 2020-12-08 09:57

I\'m trying to print a list of Strings all padded to the same width.

In C, I would use something like printf(\"%40s\", cstr), where cstr is a C string.<

6条回答
  •  没有蜡笔的小新
    2020-12-08 10:16

    Here's my solution, specific to String, but I'm sure someone smarter than I could make it more generic.

    extension String {
        func frontPadding(toLength length: Int, withPad pad: String, startingAt index: Int) -> String {
            return String(String(self.reversed()).padding(toLength: length, withPad: pad, startingAt: index).reversed())
        }
    }
    

提交回复
热议问题