How to use appendFormat to format a string in Swift?

kobuchi picture kobuchi · Apr 21, 2015 · Viewed 7.4k times · Source

I want to append a string to a NSMutableString using appendFormat, inserting white spaces to get a minimum length for my string.

In objective-c, i just used

[text.mutableString appendFormat:@"%-12s", "MyString"];

and I would get

"MyString    "

But in Swift, I tried

text.mutableString.appendFormat("%-12s", "MyString")

and I get everything, but not "MyString ". It appears some random characters that I do not know where it came from.

Is there anyone who knows why that happens, and what I should do?

Thank you guys!

Answer

Adam S picture Adam S · Apr 21, 2015

Through Ken's explanation that a Swift String object is not equivalent to the Objective-C C-style string (a null-terminated array of char) I found this answer which shows how to convert a Swift String object into a Cstring, which the %-12s formatting works correctly on.

You can use your existing formatting string as follows:

text.mutableString.appendFormat("%-12s", ("MyString" as NSString).UTF8String)

Some examples:

var str = "Test"
str += String(format:"%-12s", "Hello")
// "Test–yç       " (Test, a dash, 11 random characters)

var str2 = "Test"
str2 += String(format:"%-12@", "Hello")
// "TestHello" (no padding)

var str3 = "Test"
str3 += String(format:"%-12s", ("Hello" as NSString).UTF8String)
// "TestHello       " ('Hello' string is padded out to 12 chars)