Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

In Swift, the best I could come up is this:

line += String(format: "%40s",string.cStringUsingEncoding(<someEncoding>))

Is there a better way ?

question from:https://stackoverflow.com/questions/32338137/padding-a-swift-string-for-printing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
185 views
Welcome To Ask or Share your Answers For Others

1 Answer

For Swift >= 3

line += string.padding(toLength: 40, withPad: " ", startingAt: 0)

For Swift < 3

NSString has the stringByPaddingToLength: method:

line += string.stringByPaddingToLength(40, withString: " ", startingAtIndex: 0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...