Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format string with fixed length in swift

Tags:

swift

For example: var str = String(format: "%12s - %s", "key", "value")

What I want is key will hold chars of length of 12. key__________ - value

(underscore here is whitespace)

Thanks.

like image 591
PeiSong Avatar asked Dec 08 '14 11:12

PeiSong


2 Answers

As documentation said, COpaquePointer is a wrapper around an opaque C pointer. Opaque pointers are used to represent C pointers to types that cannot be represented in Swift, such as incomplete struct types.

Key is a String - native Swift type. I believe that it is better to use this Swift String function:

let testString = "bla bli blah"
testString.stringByPaddingToLength(3, withString: " ", startingAtIndex: 0) 
//output = "bla"

Swift 3

let testString = "bla bli blah"
testString.padding(toLength: 3, withPad: " ", startingAt: 0) 
//output = "bla"
like image 137
Dima Deplov Avatar answered Nov 08 '22 20:11

Dima Deplov


Basically, to format String with String(format: _:...), we can use %@:

String(format: "%@ - %@", "key", "value")

But, I believe %@ does not support "width" modifier: you cannot %12@ or such.

So, you have to convert String to COpaquePointer which can be formatted with %s:

var key = "key"
var val = "value"

var str = String(format: "%-12s - %s",
    COpaquePointer(key.cStringUsingEncoding(NSUTF8StringEncoding)!),
    COpaquePointer(val.cStringUsingEncoding(NSUTF8StringEncoding)!)
)
// -> "key          - value"
like image 21
rintaro Avatar answered Nov 08 '22 21:11

rintaro